python,给定一段英文文本,统计每个单词出现的次数,打印输出,按照词频从高到低输出
时间: 2024-05-09 13:18:17 浏览: 84
好的,这个问题可以回答。以下是Python代码:
```python
text = "This is a sample text with several words. This text can be used to test the word frequency count program in Python."
# Remove punctuation and convert to lowercase
text = text.lower()
text_no_punct = ""
for char in text:
if char.isalpha() or char.isspace():
text_no_punct += char
# Split text into words
words = text_no_punct.split()
# Count word frequency
word_counts = {}
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# Sort by frequency
sorted_words = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
# Print output
for word, count in sorted_words:
print(word, count)
```
输出结果如下,按照词频从高到低排序:
```
text 2
this 2
a 1
be 1
can 1
count 1
frequency 1
in 1
is 1
program 1
python 1
sample 1
several 1
test 1
the 1
to 1
used 1
with 1
word 1
words 1
```
阅读全文