0

我正在尝试编写一个 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

如果你的行都以一个单词开头,然后是空格分隔的整数,你可以这样做(未经测试):

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

我将强调您的代码的两个主要问题:

  1. for word in string.ascii_lowercase:和 write 一样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 回答