将词频统计数据写入到txt文件
时间: 2023-08-23 22:04:54 浏览: 55
可以使用Python内置的`open()`函数来创建一个文本文件,并将词频统计数据写入到文件中。以下是一个简单的例子:
```python
from collections import Counter
text = "Python is an interpreted high-level programming language for general-purpose programming. Created by Guido van Rossum and first released in 1991, Python has a design philosophy that emphasizes code readability, notably using significant whitespace. It provides constructs that enable clear programming on both small and large scales."
# 将文本转换为小写并按空格分割为单词
words = text.lower().split()
# 统计词频
word_freq = Counter(words)
# 打开文件,如果文件不存在则创建文件
with open('word_freq.txt', 'w') as f:
# 将词频统计数据写入到文件
for word, freq in word_freq.items():
f.write(f'{word}: {freq}\n')
```
这个例子中,我们首先使用之前提到的方法统计了文本中每个单词出现的次数。接着,我们使用`with`语句打开一个名为`word_freq.txt`的文件,并以写入模式打开。如果该文件不存在,则会自动创建文件。然后,我们使用循环遍历词频统计数据,并使用`write()`方法将数据写入到文件中。在每一行的末尾,我们加上了一个换行符`\n`以便于分隔每一行。
需要注意的是,在这个例子中我们使用了格式化字符串`f'{word}: {freq}\n'`来将每个单词和它的出现次数格式化成一个字符串,其中`{word}`和`{freq}`分别表示单词和出现次数的变量。