0

这是列表:

keyWord = ['gold', 'diamond', 'wood']

并且,乐谱的文本文件包括如下细节。例如,文本文件的名称是 point.txt

diamond 1
copper 2
wood 3
gold 4

在文本文件中,单词和数字之间的空格由制表符分隔。

我想使用这个分数的文本文件和 python 来获得关键字列表的总点。

我的代码是这样的......

import re
open_file = open("point.txt")

points = {}
for line in open_file:
    item, score = line.split("\t")
    points[item] = int(score)
    if item == re.findall('[\w\']+', keyWord):

我不知道如何编写代码来获得正则表达式的总分。(我认为“IF”句子有问题。)

我会等待你的大力帮助。

4

2 回答 2

0

像这样的东西:

>>> lis = ['gold', 'diamond', 'wood']
>>> points = dict.fromkeys(lis,0)     #create a dict from the list with initial value as 0
>>> with open("abc") as f:            #use with context manger to open filees
...     for line in f: 
...         key,val = line.split()   # no need of regex     
...         if key in points:        #if key is present in points then increment it's value
...             points[key] += int(val)   #use points[key] syntax to access a dict
...             
>>> points
{'gold': 4, 'wood': 3, 'diamond': 1}
于 2013-05-09T06:19:43.033 回答
0

另一种方法,类似于 Ashwini 的回答:

from collections import defaultdict

points = defaultdict(int)

with open('abc.txt') as f:
    for line in f:
        if line.strip():
            key, val = line.split()
            points[key.strip()] += int(val.strip())

# If your keywords file is like this:
# diamond
# gold
# wood
# Then you can use the below snippet to read the keywords:
with open('keywords.txt') as f:
    keywords = list(line for line in f if line.strip())

# If your keywords file is like this:
# diamond, gold, wood
# silver, platinum, water
# Then use the below snippet:

keywords = []
with open('keywords.txt') as f:
    for line in f:
        if line.strip():
           for keyword in line.split(','):
                keywords.append(keyword.strip())

for i in keywords:
    print("{} {}".format(i,points.get(i,0)))
于 2013-05-09T06:27:26.977 回答