簡體   English   中英

Python 計數器單詞不是字母

[英]Python counter words not letters

我正在嘗試創建一個程序,該程序讀取文本文件並查找單個單詞的數量。 我已經解決了大部分問題,但我一直在努力讓計數器像目前那樣挑選單詞而不是字母。

import collections 

with open ("file.txt" ,"r") as myfile:
    data=myfile.read()
[i.split(" ") for i in data]

x=collections.Counter(data)

print (x)

我的目標是用空格滑動列表,這將導致每個單詞成為列表中的一個對象。 然而這並沒有奏效。

結果:

Counter({' ': 1062, 'e': 678, 't': 544, 'o': 448, 'n': 435, 'a': 405, 'i': 401, 'r': 398,       's': 329, 'c': 268, 'm': 230, 'h': 216, 'u': 212, 'd': 190, 'l': 161, 'p': 148, 'f': 107, 'g': 75, 'y': 68, '\n': 65, ',': 61, 'b': 55, 'w': 55, 'v': 55, '.': 53, 'N': 32, 'A': 20, 'T': 19, '"': 18, ')': 17, '(': 17, 'C': 17, 'k': 16, "'": 16, 'I': 16, 'x': 15, '-': 14, 'E': 13, 'q': 12, 'V': 10, 'U': 9, ';': 7, '1': 6, 'j': 5, '4': 5, 'P': 5, 'D': 5, '9': 5, 'L': 4, 'z': 4, 'W': 4, 'O': 3, 'F': 3, '5': 3, 'J': 2, '3': 2, 'S': 2, 'R': 2, '0': 1, ':': 1, 'H': 1, '2': 1, '/': 1, 'B': 1, 'M': 1, '7': 1})

您的列表理解永遠不會被分配,因此不會做任何事情。

將拆分文本傳遞給collections.Counter()

x = collections.Counter(data.split())

並且我使用了不帶參數的str.split()以確保在任意寬度的str.split()進行拆分並在拆分時也包含換行符; 例如,您的Counter()有 65 個不需要在那里的換行符。

在上下文中,更緊湊一點:

from collections import Counter

with open ("file.txt") as myfile:
    x = Counter(myfile.read().split())

print(x)

要回答標題,不要用字符串更新計數器,而是設置一個或多個字符串的列表。

然后,如果您的代碼是:

from collections import Counter
words_count = Counter("tiger")

請記住,字符串是一個列表字符。 代碼是這樣的:

from collections import Counter
words_count = Counter("t", "i", "g", "e", "r")

否則,如果您的代碼是:

from collections import Counter
words_count = Counter(["tiger"])

那么,列表元素就是完整的單詞。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM