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

アシュウィニの答えに似た別のアプローチ:

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 に答える