-2

我想编程,它打开两个文件 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

4

1 回答 1

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语句。

上面的dict-comprehension大致相当于:

dic = {}
for line in f2:
    word, val  = line.split()
    dic[word] = int(val)
于 2013-09-07T08:12:17.517 回答