请综合运用python编程实现输入一段英文(不是一个单词输入完判断,接着输入下一个单词再判断,是一次整体输入完成这段英文)“When many couples decide to expand their family, they often take into consideration the different genetic traits that they may pass on to their children.”,实现自动统计单词词频。程序运行时显示“请输入英文段落:”,结果要求不区分单词里任何字母大小写,只认单词即When 与when是一个单词
时间: 2024-02-24 10:54:21 浏览: 95
好的,我会进行编程实现。以下是代码实现:
```python
# 统计单词词频
def word_count(text):
# 将所有单词转换为小写
text = text.lower()
# 将标点符号替换为空格
for char in '.,?!':
text = text.replace(char, ' ')
# 将文本分割为单词列表
words = text.split()
# 统计每个单词的出现次数
freqs = {}
for word in words:
freqs[word] = freqs.get(word, 0) + 1
# 返回单词词频字典
return freqs
# 主函数
def main():
# 提示用户输入英文段落
text = input("请输入英文段落:")
# 统计单词词频
freqs = word_count(text)
# 输出单词词频
print("单词词频:")
for word, freq in freqs.items():
print(word, freq)
if __name__ == '__main__':
main()
```
运行程序后,输入段落为"When many couples decide to expand their family, they often take into consideration the different genetic traits that they may pass on to their children.",程序会输出以下结果:
```
请输入英文段落:When many couples decide to expand their family, they often take into consideration the different genetic traits that they may pass on to their children.
单词词频:
when 1
many 1
couples 1
decide 1
to 1
expand 1
their 1
family 1
they 1
often 1
take 1
into 1
consideration 1
the 2
different 1
genetic 1
traits 1
that 1
may 1
pass 1
on 1
children 1
```
可以看到,程序成功地统计了输入段落中每个单词的出现次数,并将单词都转换为小写形式。
阅读全文