处理python中的数据

时间:2013-05-09 06:15:50

标签: python regex list

以下是清单:

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'句子有错。)

我会等你的帮助。

2 个答案:

答案 0 :(得分: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}

答案 1 :(得分: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)))