用于字数统计,平均字长,单词频率和以字母表字母开头的单词频率的Python程序



需要编写一个分析文件并计数的 Python 程序:

  • 字数
  • 单词的平均长度
  • 每个单词出现多少次
  • 字母表中每个字母开头的单词数

我有代码可以做前两件事:

with open(input('Please enter the full name of the file: '),'r') as f:
w = [len(word) for line in f for word in line.rstrip().split(" ")]
total_w = len(w)
avg_w = sum(w)/total_w
print('The total number of words in this file is:', total_w)
print('The average length of the words in this file is:', avg_w)

但我不确定如何做其他事情。任何帮助,不胜感激。

顺便说一句,当我说"有多少个单词以字母表的每个字母开头"时,我的意思是有多少个单词以"A"开头,有多少单词以"B"开头,有多少单词以"C"开头,等等一直到"Z"。

有很多方法可以实现这一点,更高级的方法包括对文本及其单词进行初始简单收集,然后使用 ML/DS 工具处理数据,您可以使用这些工具推断更多统计数据(例如"新段落主要以 X 个单词开头"/"X 个单词大多以 Y 单词开头/后面"等(

如果你只需要非常基本的统计数据,你可以在迭代每个单词时收集它们,并在最后进行计算,例如:

stats = {
'amount': 0,
'length': 0,
'word_count': {},
'initial_count': {}
}
with open('lorem.txt', 'r') as f:
for line in f:
line = line.strip()
if not line:
continue
for word in line.split():
word = word.lower()
initial = word[0]
# Add word and length count
stats['amount'] += 1
stats['length'] += len(word)
# Add initial count
if not initial in stats['initial_count']:
stats['initial_count'][initial] = 0
stats['initial_count'][initial] += 1
# Add word count
if not word in stats['word_count']:
stats['word_count'][word] = 0
stats['word_count'][word] += 1
# Calculate average word length
stats['average_length'] = stats['length'] / stats['amount']

在线演示在这里

你得到了一个有趣的挑战,我为问题 3 提出了一个命题,一个单词在字符串中出现了多少次。这段代码根本不是最佳的,但它确实有效。

我也使用了文件text.txt

编辑:注意到我忘记创建单词列表,因为它保存在我的 RAM 内存中

with open('text.txt', 'r') as doc:
print('opened txt')
for words in doc:
wordlist = words.split()     
for numbers in range(len(wordlist)):
for inner_numbers in range(len(wordlist)):
if inner_numbers != numbers:
if wordlist[numbers] == wordlist[inner_numbers]:
print('word: %s == %s' %(wordlist[numbers], wordlist[inner_numbers]))

回答问题四:在你创建了一个包含所有单词的列表之后,这个问题并不难,因为字符串可以被视为一个列表,你可以通过简单地做string[0]来轻松获取字符串的第一个字母,如果它是一个包含字符串的列表stringList[position of word][0]

for numbers in range(len(wordlist)):
if wordlist[numbers][0] == 'a':
print(wordlist[numbers])

最新更新