2013-05-09 2 views
0

에 데이터를 다루는 것은 목록입니다. 예를 들어, 텍스트 파일의 이름은 point.txt입니다.파이썬 여기

diamond 1 
copper 2 
wood 3 
gold 4 

텍스트 파일에서 단어와 숫자 사이의 간격은 탭으로 구분됩니다.

나는이 점수의 텍스트 파일을 파이썬과 함께 사용하여 키워드 목록의 총점을 얻고 싶습니다.

내 코드는 다음과 같이 간다 ...

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

점 [항목]하지 점 (항목) – jamylak

답변

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} 
+0

내가 파일에서 문양을 읽으려면 어떻게 나는 각 줄의 합계를 얻는다? 리스 파일에 20 줄의리스트가 있다면? – PrimingRyan

+0

각 줄의 합계를 풀었습니다. – PrimingRyan

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))) 
+0

조언 해 주셔서 감사합니다. 나에게 새로운 개념이 있다는 것을 이해하는 데 약간의 시간이 걸릴 것이다. – PrimingRyan

+0

내 게시물에서 score txt 파일과 같은 파일에서 키워드 목록을 읽으려는 경우. 어떻게 각 라인의 총점을 얻을 수 있습니까? 예를 들어 키워드 목록에 'gold', 'diamond', 'wood', 'copper', 'plastic', 'rubber'...와 같은 키워드 목록이있는 경우 .... 키워드 목록에 20 줄의 목록이있는 경우 파일 .....? – PrimingRyan