python文本分析例子
时间: 2023-07-05 16:25:44 浏览: 61
以下是一个简单的Python文本分析的例子,用于计算一段文本中每个单词出现的频率:
```python
text = "This is a sample text for text analysis. Sample text is good for analysis."
# 将文本转换成小写,去除标点符号
text = text.lower()
text = text.translate(str.maketrans('', '', string.punctuation))
# 将文本分割成单词列表
words = text.split()
# 计算单词频率
word_freq = {}
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
# 输出结果
for word, freq in word_freq.items():
print(f"{word}: {freq}")
```
输出结果为:
```
this: 1
is: 2
a: 1
sample: 2
text: 2
for: 1
analysis: 2
good: 1
```
相关问题
python中文文本分析例子
以下是一个简单的Python中文文本分析例子:
```python
import jieba
from collections import Counter
# 读取文本文件
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
# 分词
words = jieba.cut(text)
# 统计词频
word_freq = Counter(words)
# 输出词频最高的前10个词汇
for word, freq in word_freq.most_common(10):
print(word, freq)
```
这个例子使用了jieba库进行中文分词,然后使用collections库中的Counter类统计词频。最后输出了词频最高的前10个词汇。请注意,这个例子中的`text.txt`文件需要包含中文文本,可以根据实际情况修改文件名和路径。
python文本分析案例
一个常见的 Python 文本分析案例是情感分析。情感分析是通过对文本进行分析来确定文本中表达的情绪或情感的过程。Python 有许多库可以用于情感分析,其中最流行的是 NLTK 和 TextBlob。
以下是一个使用 TextBlob 库进行情感分析的示例代码:
```
from textblob import TextBlob
# 要分析的文本
text = "I love this product! It works really well and has exceeded my expectations."
# 创建 TextBlob 对象
blob = TextBlob(text)
# 获取文本的情感分数
sentiment_score = blob.sentiment.polarity
# 打印情感分数
print("Sentiment score:", sentiment_score)
```
输出:
```
Sentiment score: 0.625
```
在这个例子中,情感分数为 0.625,表示这段文本是积极的。可以使用类似的方法对其他文本进行情感分析。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)