代码没有报错,表格也生成生程,就是只有表头,没有生成竖列
from pathlib import Path
import jieba
import csv
def senti(text):
pos_num = 0
neg_num = 0
words = jieba.lcut(text)
for word in words:
if word in poss:
pos_num = pos_num + 1
if word in negs:
neg_num = neg_num + 1
return {"pos": pos_num, "neg": neg_num}
#新建csv
csvf = open('data/txts情感计算.csv', 'a+', encoding='utf-8')
fieldnames = ['name', 'text', 'pos', 'neg']
writer = csv.DictWriter(csvf, fieldnames=fieldnames)
writer.writeheader()
#读取词典文件
poss = open('data/英文情感词/正面.txt', encoding='utf-8').read().split('\n')
negs = open('data/英文情感词/负面.txt', encoding='utf-8').read().split('\n')
#批量获取文件路径
txtdir = Path().cwd().joinpath('S220', 'txts')
for file in txtdir.glob('*.txt'):
file = str(file)
text = open(file, encoding='utf-8').read()
raw = file.split('_')[-1]
name = raw[-1]
score = senti(text)
data = {'name':name,
'text':text,
'pos':score['pos'],
'neg':score['neg']}
writer.writerow(data)
#关闭csv
csvf.close()
1·怎么样可以让情感分析匹配单词的时候忽略原文本的字母大小写呢
2·这个for循环为什么不能将name放入Excel表头
转小写
def senti(text):
pos_num = 0
neg_num = 0
words = jieba.lcut(text)
for word in words:
word=word.lower()##转小写
if word in poss:
pos_num = pos_num + 1
if word in negs:
neg_num = neg_num + 1
return {"pos": pos_num, "neg": neg_num}
#新建csv
csvf = open('data/txts情感计算.csv', 'w', encoding='utf-8', newline='')###添加newline='',要不会写入空行
fieldnames = ['name', 'text', 'pos', 'neg']
writer = csv.DictWriter(csvf, fieldnames=fieldnames)
writer.writeheader()
#读取词典文件
poss = open('data/英文情感词/正面.txt', encoding='utf-8').read().lower().split('\n')##全部转小写后再split
negs = open('data/英文情感词/负面.txt', encoding='utf-8').read().lower().split('\n')##全部转小写后再split
```python
def senti(text):
pos_num = 0
neg_num = 0
words = jieba.lcut(text)
for word in words:
word = word.lower() # 将单词转换为小写字母
if word in poss:
pos_num = pos_num + 1
if word in negs:
neg_num = neg_num + 1
return {"pos": pos_num, "neg": neg_num}
通过将所有单词转换为小写字母,任数将匹配配积极和消极单词,而不考究最初文本中的大写或小写字母。
forexcel表头表头循环能name,因为因为因为没有csv.DictWriter对象定义定义为名称名称。。。csv.DictWriter对象对象对象使用使用使用参数参数定义定义定义定义定义fieldnames定义定义定义使用文件文件文件脚本中,fieldnames列表被定义为['name', 'text', 'pos', 'neg'],这意味着表头行将包含这四个字段名的四列。
如果想在CSV文件的表头行中添加name,需要将其添加到fieldnames列表中,如下所示:
```css
fieldnames = ['name', 'text', 'pos', 'neg']
然后,需要确保传递给writer.writerow(data)的data字典包含name的键值对,如下所示:
```ruby
data = {'name':name,
'text':text,
'pos':score['pos'],
'neg':score['neg']}
```
通过这些修改,输出的CSV文件将具有五列的表头行:name、text、pos、neg和一个额外的列用于文件名。