0

テキストを取り込み、1 行ずつ読み取ることができる Python コードを作成しようとしています。各行では、単語はキーとして辞書に入力され、数字はリストとして割り当てられた値である必要があります。たとえば、ファイルは次のような形式の何百もの行で構成されます。

ピーター 17 29 24 284 72

理想的には、"Peter" という名前がディクショナリのキーであり、値がdict[Peter]: [17, 19, 24, 284,7273].

これまでのところ、私の問題は数字を追加することです。それらをキー値に割り当てる方法がわかりません。

    def wordDict(filename):
        inFile=open(filename, 'r')
        line=inFile.readline()
        while line: 
            txtWords = line.split() # splits at white space
            wordScores={} # make dict
            scoreList=[]
            for word in txtWords:
                word.lower() # turns word into lowercase
                if word in string.ascii_lowercase:   #if word is alphabetical 
                    if word not in wordScores.keys():
                        wordScores=wordScores[word] # add the key to dictionary

---------- 私が持っているすべて

4

3 に答える 3

1

Python 3.2 を使用する場合:

with open("d://test.txt", "r") as fi:  # Data read from a text file is a string
    d = {}
    for i in fi.readlines():
        # So you split the line into a list
        temp = i.split()
        # So, temp = ['Peter', '17', '29', '24', '284', '72']

        # You could split 'temp' like so:
        #    temp[0] would resolve to 'Peter'
        #    temp[1] would resolve to ['17', '29', '24', '284', '72']
        name, num = temp[0], temp[1:]

        # From there, you could make temp[0] the key and temp[1:] the value.
        # But: notice that the numbers are still represented as strings.
        # So, we use the built-in function map() to turn them into integers.
        d[name] = [map(int, num)]
于 2012-11-30T05:08:26.583 に答える
0

行がすべて 1 つの単語で始まり、次にスペースで区切られた整数である場合は、次のことができます (未テスト):

myDict = {}
with open('inFile.txt','r') as inFile:
    for line in inFile:
        line = line.split()
        name = line[0].lower()
        if name not in myDict:
            myDict[name] = map(int,line[1:])
于 2012-11-30T01:49:40.987 に答える
0

コードの 2 つの主な問題を強調します。

  1. for word in string.ascii_lowercase:は書き込みと同じfor 'hello' in ['a','b,'c']:ですが、期待どおりにはなりません。ループは決して実行されません。

  2. wordScores = wordScores[word]これはキーに何も追加していません。おそらくwordScores[word] = [].

代わりにこれを試してください:

from collections import defauldict
words = defaultdict(list)

with open('somefile.txt') as f:
   for line in f:
      if line.strip():
         bits = line.split()
         if bits[0].isalpha():
             words[bits[0].lower()] += bits[1:]   
于 2012-11-30T01:58:49.627 に答える