我想要编程,打开两个文件A.txt和B.txt,在文件A中有句子如:三升牛奶,在B档中有值,如三个2,升3,1 ,牛奶4 我想打开第一个文件并检查单词值并添加这些值并打印,如果值加起来为5.到目前为止,我这样做了:
count=0
with open('shopping.txt') as s:
with open('syllables.txt') as f:
words = {}
syllables = {}
for line in f:
word, syla = line.split()
words[word] = syla
syllables[syla] = word
for lines in s:
lines=lines.strip()
lines=lines.split()
for i in lines:
lines=words[i]
print(lines)
我得到的是单词的值,但是在一行中有1个值,在下一行中有另一个值。
文件A包含:
three litres of milk
colour fast shampoo
文件B包含:
sam 2
apple 3
three 2
litres 1
of 1
milk 1
colour 3
fast 1
shampoo 4
我想打印总值为5的行,就像第一行总计5
一样答案 0 :(得分:1)
with open('A.txt') as f1, open('B.txt') as f2:
#create a dict from fileB and don't forget to convert the count to an integer
dic = {word : int(val) for word, val in (line.split() for line in f2)}
#now iterate over each line in fileA
for line in f1:
words = line.split()
#get the count using `sum()`
#dict.get would return 0 if key is not found in dic
count = sum(dic.get(word, 0) for word in words)
if count == 5:
print (line, end='') #or `print (line.strip())`
<强>输出:强>
three litres of milk
注意:
1。 str.split()
负责处理空格,因此不需要str.strip()
。
2。在py3.x和py2.7 +中,不需要嵌套with
语句。
上述字典理解大致相当于:
dic = {}
for line in f2:
word, val = line.split()
dic[word] = int(val)