2017-01-30 12 views
0

私の目標は、ファイルを読み込み、ユーザーが要求した対応する情報を返すことです。ファイルを読み込んでPythonで文字列を返す

5.5 6.3 4.0 5.2 5.1

4.6 4.8 5.3:たとえば、私のテキストファイルには、この(それは年とその年からの留学生の高さを表している)ように見えます5.6 6.0

3.8 4.9 6.0 5.8 5.7

基本的に2013年を入力すると、その年に対応する高さのリスト(下の行)を返すようにします。しかし、私は文字列のリストを印刷することはできません。いくつかの助けが素晴らしいだろう。

#read in text file 
f = open("students.txt") 
#ask for student year 
year = input("Enter the year for the data you want to receive:") 
#check to see if year is avialble 
line = f.readline() 
while True: 
    line = f.readline().split() 
    if line: 
     if line == year: 
      print(line) 
    else: 
     break 
     print("No data") 

答えて

0

f.readline().split()を実行すると、リストが表示されます。最初の行はline == ['2013']のようになります。一方、年は文字列です。ユーザーが2013を入力した場合は、type(year) == <class 'str'>となります。type(line) == <class 'list'>です。それらは決して等しくないので、if節は決してTrueであり、行は決して印刷されません。

#read in text file 
f = open("students.txt") 
#ask for student year 
year = input("Enter the year for the data you want to receive:") 
#check to see if year is available 
for line in f.readlines(): 
    if year in line: 
     f.readline() 
     print (f.readline()) 
     break 

高さが2,000を超える学生がいる場合、上記のコードは機能しません。

0

代わりにすべてのエントリを辞書に読み込んでみてください。それから、年ごとに照会するのが簡単です。

def readentries(f):  
    # read until we get `StopException` i.e. end of file 
    while True: 
     try: 
      # take two lines from the file and strip newlines 
      # and split heights by spaces to give a list of heights 
      yield next(f).strip(), next(f).strip().split() 
     except StopIteration: 
      # break out of the infinite while loop 
      break 

with open('heights.txt') as f: 
    entries = dict(readentries(f)) 

year = input("Enter the year for the data you want to receive: ") 

# query dict for supplied entry 
if year in entries: 
    print('for year %s we have heights %s ' % (year, ', '.join(entries[year]))) 
else: 
    print('no data') 

変数をfloat個の変数に変換したい場合があります。これは簡単に追加できます。

0

単純なアプローチは、ファイルのすべての行をリストに読み込んだり、必要な年に基づいてリスト内の索引を見つけて、次の行を取得することです。

with open('students.txt', 'r') as f: 
    data = [i.strip() for i in f] # strip trailing space 

year = input("Enter year: ") 
try: 
    # find index, get the next line 
    line = data[data.index(year) + 1] 
    # split on whitespace, apply float() 
    item_list = [float(i) for i in line.split()] 
except ValueError: # raised if year not found 
    print("No relevant data") 
0

次の空でない行は、必要な年である行の後に印刷します。

with open("grade.txt", "r") as file: 
    year = [] 
    height = [] 
    for i in file: 
     if len(i.strip("\n")) == 4: 
      year.append(i.strip("\n")) 
     elif i != "\n": 
      height.append(i.strip("\n").split(" ")) 
    ydict = {year[i]: height[i] for i in range(len(year))} 

print(ydict['2013']) 
0

最初に次に、偶数行(年)を辞書のキー(ゼロから始まる)と奇数の行(高さ)を辞書の値として追加するだけです。

year = input("Enter the year for the data you want to receive:") 
with open("students.txt") as f: 
    # read stripped file lines into list keeping only those that contain data 
    data = [line.strip() for line in f.readlines() if line.strip() != ''] 
# build a dict from the data using list slicing to get the years (keys) and heights (values) 
data_dict = dict(zip(data[0::2], data[1::2])) 
# print the heights if the year exists otherwise 'No data.' 
print(data_dict.get(str(year)) if data_dict.get(str(year)) else 'No data.') 
0

データは、いくつかの空白行やタブが含まれているので、あなたがそれをきれいにしたいと思う:あなたは、2つのリストを作成し、thheファイルの行を反復処理することにより、辞書を構築することができ

year = "2013" 

with open("students.txt") as f: 
    stop = False 
    for line in f: 
     line = line.rstrip("\n") 
     if line == year: 
      stop = True 
     else: 
      if line and stop: 
       print line.split() 
       break 

    if not stop: 
     print "No data for year {}.".format(year) 
関連する問題