0

我想要做的是从文件中读取,然后对于每个单词,将其连同其出现次数一起附加到字典中。

例子:

'今天​​是星期日。明天不是星期天。

我的字典会是这样的: {'today': 1, 'is': 2, 'sunday': 2, 'tomorrow': 1, 'not': 1}

我要解决的方法是使用 readline 和 split 创建一个列表,然后将每个元素及其值附加到一个空字典中,但到目前为止它并没有真正起作用。这是我到目前为止所拥有的,虽然它不完整:

file = open('any_file,txt', 'r')

for line in file.readline().split():
     for i in range(len(line)):
         new_dict[i] = line.count(i)  # I'm getting an error here as well, saying that  
return new_dict                       # I can't convert int to str implicitly 

这样做的问题是,当我的字典在读取每一行时更新时,单词的值不会累积。因此,如果在另一行 'sunday' 出现 3 次,我的字典将包含 {'sunday': 3} 而不是 {'sunday': 5}。有什么帮助吗?我不知道从这里去哪里,而且我对这一切都很陌生。

4

4 回答 4

2

您正在寻找collections.Counter.

例如:

from itertools import chain

with open("file.txt") as file:
    Counter(chain.from_iterable(line.split() for line in file))

(也使用生成器表达式。)itertools.chain.from_iterable()

请注意,您的示例仅适用于第一行,我认为这不是故意的,并且此解决方案适用于整个文件(显然交换它很简单)。

于 2013-02-04T03:56:49.410 回答
1

这是一个不处理标点符号的简单版本

from collections import Counter
counter = Counter()
with open('any_file,txt', 'r') as file:
    for line in file:
        for word in line.split():
            counter[word] += 1

也可以这样写:

from collections import Counter
counter = Counter(word for line in file for word in line.split())

这是解决问题的一种方法dict

counter = {}
with open('any_file,txt', 'r') as file:
    for line in file:
        for word in line.split():
            if word not in counter:
                counter[word] = 1
            else:
                counter[word] += 1
于 2013-02-04T04:00:47.047 回答
0

你使用 Python 3 还是 Python 2.7?

如果是,请使用集合库中的计数器:

import re
from collections import Counter
words = re.findall('\w+', open('any_file.txt').read().lower())
Counter(words).most_common(10)

但是你得到了元组列表。将元组列表转换为字典应该很容易。

于 2013-02-04T04:00:27.240 回答
0

尝试这个

 file = open('any_file.txt', 'r')
 myDict = {}
 for line in file:
     lineSplit = line.split(" ")
     for x in xrange(len(lineSplit)):
         if lineSplit[x] in myDict.keys(): myDict[lineSplit[x]] += 1
         else: myDict[lineSplit[x]] = 1

 file.close()

 print myDict
于 2013-02-04T04:07:52.407 回答