使用字典替换标记化系列中的单词

2024-05-14 06:23:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新的Python编码,所以请对我容易。我有一个标记化的熊猫系列,看起来像这样:

reviews = [['bad', 'movie', 'it', 'was', 'turrible'],['bad', 'acting', 'in' 'it'], ['ok', 'experience'],...]

我有一本这样的字典:

d = {'turrible':'terrible', 'ok':'okay',...}

评论中出现在词典关键字中的任何单词都应替换为词典值。因此,预期输出为:

reviews = [['bad', 'movie', 'it', 'was', 'terrible'],['bad', 'acting', 'in', 'it'], ['okay', 'experience'],...]

我搜索了几个小时,尝试了这些解决方案,但没有得到预期的结果。你知道吗

试验1:

pattern = re.compile(r'\b(' + '|'.join(d.keys()) + r')\b')
result = pattern.sub(lambda x: d[x.group()], reviews)

Output: error: incomplete escape \u

试验2:

def replaceWords(text,wdict):
return ''.join(wdict.get(word,word) for word in text)
replaceWords(docs,d)
Output: TypeError unhashable type: 'list'

试用3-没有错误消息,但未获得预期输出:

reviews = reviews.replace(d)

试验4:

reviews = reviews.replace(d, regex=True)
error: missing ), unterminated subpattern

任何帮助都将不胜感激。你知道吗

编辑:修正了评论系列的结构


Tags: in评论itokmovie词典wordexperience
1条回答
网友
1楼 · 发布于 2024-05-14 06:23:30
>>> reviews = ['bad' 'movie' 'it' 'was' 'terrible','bad' 'acting' 'in' 'it',
   ...:  'okay' 'experience']

>>> reviews
 ['badmovieitwasterrible', 'badactinginit', 'okayexperience']

可能不是你想要的。你知道吗

相关问题 更多 >