我有一个csv文件(或txt文件)中的语料库(30,000个客户评论)。这意味着每个客户评论都是文本文件中的一行。一些例子是:通过使用Python插入代码字来修改语料库
- 这自行车是惊人的,但制动很差
- 该制冰机的伟大工程,这个价格是非常合理的,从制冰机
- 食物是一些不好的 气味真棒,但水是很不礼貌的
我想这些文本更改为以下:
- 这自行车是惊人的利好,但制动很差负
- 该制冰机的伟大工程正,价格是非常合理 正,从制冰机
- 食物是真棒正一些不好的负气味,但水是非常粗鲁的
我有两个单独的名单(词汇)的积极的话和消极的话。例如,一个文本文件包含了这样积极的话为:
- 惊人
- 伟大
- 真棒
- 非常酷
- 合理
- 漂亮
- 快速
- 美味
- 种
而且,一个文本文件包含这样的负面词为:
- 粗鲁
- 差
- 最坏
- 脏
- 慢
- 坏
因此,我需要读取客户评论的Python脚本:当找到任何正面词语时,在正面词语后面插入“正面”;当找到任何一个否定词,然后在正词后插入“NEGATIVE”。
这是我迄今测试过的代码。这可行(请参阅下面的代码中的我的意见),但需要改进才能满足上述需求。
具体来说,my_escaper
的作品(这个代码发现这样的话便宜又好,用便宜的POSITIVE和良好的正面代替),但问题是我有两个文件(词典),每个文件包含大约1000个正面/负面的词。所以我想要的是代码从词典中读取这些单词列表,在语料库中搜索它们,并且替换语料库中的这些单词(例如,从“好”到“良好”,从“坏”到“坏”负”)。
#adapted from http://stackoverflow.com/questions/6116978/python-replace-multiple-strings
import re
def multiple_replacer(*key_values):
replace_dict = dict(key_values)
replacement_function = lambda match: replace_dict[match.group(0)]
pattern = re.compile("|".join([re.escape(k) for k, v in key_values]), re.M)
return lambda string: pattern.sub(replacement_function, string)
def multiple_replace(string, *key_values):
return multiple_replacer(*key_values)(string)
#this my_escaper works (this code finds such words as cheap and good and replace them with cheap POSITIVE and good POSITIVE), but the problem is that I have two files (lexicons), each containing about thousand positive/negative words. So what I want is that the codes read those word lists from the lexicons, search them in the corpus, and replace those words in the corpus (for example, from "good" to "good POSITIVE", from "bad" to "bad NEGATIVE")
my_escaper = multiple_replacer(('cheap','cheap POSITIVE'), ('good', 'good POSITIVE'), ('avoid', 'avoid NEGATIVE'))
d = []
with open("review.txt","r") as file:
for line in file:
review = line.strip()
d.append(review)
for line in d:
print my_escaper(line)
您可能想尝试使其更具可读性。 – miradulo
它以什么方式工作,但无法满足您的需求? – TigerhawkT3
我已经添加了一个关于什么可行,需要更多的解释。希望这对你有意义。谢谢。 – kevin