【问题标题】:Python count of words by word lengthPython按字长计算字数
【发布时间】:2021-04-14 19:38:58
【问题描述】:

我收到了一个带有文本的 .txt 文件。我已经清理了文本(删除了标点符号、大写字母、符号),现在我有了一个带有单词的字符串。 我现在正在尝试获取字符串上每个项目的字符数len()。然后绘制一个图,其中 N 个字符位于 X 轴上,Y 轴是具有此类 N len() 个字符的单词数

到目前为止我有:

text = "sample.txt"

def count_chars(txt):
    result = 0
    for char in txt:
        result += 1     # same as result = result + 1
    return result

print(count_chars(text))

到目前为止,这是在寻找文本的总数 len(),而不是按单词。

我想获得类似 Counter Counter() 的函数,它返回带有在整个文本中重复次数的单词。

from collections import Counter
word_count=Counter(text)

我想获取每个单词的字符数。一旦我们有了这样的计数,绘图应该会更容易。

谢谢,有什么帮助!

【问题讨论】:

  • 你能解释一下吗?你想要文本每个单词的总长度吗?
  • 像句子apple tree 总数应该是9?
  • @Zachary 想象你提到的句子是 .txt 文件。我想得到:apple, 5 tree, 4 然后按len()分组单词
  • 您要求“绘制一个图,其中 N 个字符在 X 轴上,Y 轴是具有这样 N len() 个字符的单词的数量”我>。我查看了您已接受的答案,但我无法理解构建一个键为 words 且值为单词长度的字典对追求您的意图有何帮助。

标签: python matplotlib


【解决方案1】:

好的,首先你需要打开sample.txt文件。

with open('sample.txt', 'r') as text_file:
    text = text_file.read()

text = open('sample.txt', 'r').read()

现在我们可以计算文本中的单词并将其放入例如字典中。

counter_dict = {}
for word in text.split(" "):
    counter_dict[word] = len(word)
print(counter_dict)

【讨论】:

  • OP 请求 “绘制一个图,其中 N 个字符在 X 轴上,Y 轴是具有这样 N 个字符的字数 len()”。以 words 为键且以字长为值的字典对追求 OP 的意图有何帮助?
【解决方案2】:

看起来接受的答案并没有解决问题,因为它是由提问者提出的

然后绘制一个图,其中 N 个字符在 X 轴上,Y 轴是具有这样 N len() 个字符的单词的数量

import matplotlib.pyplot as plt

# ch10 = ... the text of "Moby Dick"'s chapter 10, as found
# in https://www.gutenberg.org/files/2701/2701-h/2701-h.htm

# split chap10 into a list of words,
words = [w for w in ch10.split() if w]
# some words are joined by an em-dash
words = sum((w.split('—') for w in words), [])
# remove suffixes and one prefix
for suffix in (',','.',':',';','!','?','"'):
    words = [w.removesuffix(suffix) for w in words]
words = [w.removeprefix('"') for w in words]

# count the different lenghts using a dict
d = {}
for w in words:
    l = len(w)
    d[l] = d.get(l, 0) + 1

# retrieve the relevant info from the dict 
lenghts, counts = zip(*d.items())

# plot the relevant info
plt.bar(lenghts, counts)
plt.xticks(range(1, max(lenghts)+1))
plt.xlabel('Word lengths')
plt.ylabel('Word counts')
# what is the longest word?
plt.title(' '.join(w for w in words if len(w)==max(lenghts)))

# T H E   E N D

plt.show()

【讨论】:

  • 你是对的!我在问一个情节。上面的答案帮助我自己找到了解决方案,但你的答案更完整。如果其他人发现这篇文章,他们可以在您的解决方案中看到绘图;因此,我认为它应该成为解决方案。我也测试过,非常棒!我喜欢标题如何显示最长的单词。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-05-12
  • 1970-01-01
  • 2012-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多