[英]appending a list from a read text file python3
我正在嘗試讀取txt文件並根據文本創建字典。 樣本txt文件為:
John likes Steak
John likes Soda
John likes Cake
Jane likes Soda
Jane likes Cake
Jim likes Steak
我想要的輸出是一個字典,其名稱為鍵,而“ likes”為各個值的列表:
{'John':('Steak', 'Soda', 'Cake'), 'Jane':('Soda', 'Cake'), 'Jim':('Steak')}
我繼續遇到將我的剝離單詞添加到列表中的錯誤,並嘗試了幾種不同的方法:
pred = ()
prey = ()
spacedLine = inf.readline()
line = spacedLine.rstrip('\n')
while line!= "":
line = line.split()
pred.append = (line[0])
prey.append = (line[2])
spacedLine = inf.readline()
line = spacedLine.rstrip('\n')
並且:
spacedLine = inf.readline()
line = spacedLine.rstrip('\n')
while line!= "":
line = line.split()
if line[0] in chain:
chain[line[0] = [0, line[2]]
else:
chain[line[0]] = line[2]
spacedLine = inf.readline()
line = spacedLine.rstrip('\n')
有任何想法嗎?
這樣做(不需要先將整個文件讀入內存):
likes = {}
for who, _, what in (line.split()
for line in (line.strip()
for line in open('likes.txt', 'rt'))):
likes.setdefault(who, []).append(what)
print(likes)
輸出:
{'Jane': ['Soda', 'Cake'], 'John': ['Steak', 'Soda', 'Cake'], 'Jim': ['Steak']}
另外,為簡化操作,您可以使用一個臨時collections.defaultdict
:
from collections import defaultdict
likes = defaultdict(list)
for who, _, what in (line.split()
for line in (line.strip()
for line in open('likes.txt', 'rt'))):
likes[who].append(what)
print(dict(likes)) # convert to plain dictionary and print
您的輸入是一個序列序列。 首先解析外部序列,然后解析每個項目。
您的外部順序是:
Statement
<empty line>
Statement
<empty line>
...
假定f
是帶有數據的打開文件。 閱讀每個語句並返回它們的列表:
def parseLines(f):
result = []
for line in f: # file objects iterate over text lines
if line: # line is non-empty
result.append(line)
return result
請注意,上面的函數接受更廣泛的語法:它允許非空行之間的任意多個空行,以及一行中的兩個非空行。 但是它確實接受任何正確的輸入。
然后,您的陳述是一個三元組: X likes Y
通過按空格將其拆分並檢查結構來對其進行解析。 結果是正確的(x, y)
。
def parseStatement(s):
parts = s.split() # by default, it splits by all whitespace
assert len(parts) == 3, "Syntax error: %r is not three words" % s
x, likes, y = parts # unpack the list of 3 items into varaibles
assert likes == "likes", "Syntax error: %r instead of 'likes'" % likes
return x, y
列出每個語句對的列表:
pairs = [parseStatement(s) for s in parseLines(f)]
現在,您需要按鍵對值進行分組。 讓我們使用defaultdict
為任何新密鑰提供默認值:
from collections import defaultdict
the_answer = defaultdict(list) # the default value is an empty list
for key, value in pairs:
the_answer[key].append(value)
# we can append because the_answer[key] is set to an empty list on first access
因此,在這里the_answer
是您所需要的,只有它使用列表而不是元組作為dict值。 這足以讓您了解您的作業。
dic={}
for i in f.readlines():
if i:
if i.split()[0] in dic.keys():
dic[i.split()[0]].append(i.split()[2])
else:
dic[i.split()[0]]=[i.split()[2]]
print dic
這應該做。
在這里,我們通過f.readlines
f
作為文件對象進行f.readlines
,並在每一行上使用split的第一部分作為鍵,而split的最后部分作為值來填充字典
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.