使用python将句子中的每个单词替换为单词索引

Posted

技术标签:

【中文标题】使用python将句子中的每个单词替换为单词索引【英文标题】:replacing each words in sentence into the words index using python 【发布时间】:2020-04-16 02:24:41 【问题描述】:

我有两个 csv 文件,其中一个包含如下所示的句子

                         sentences
0  yes good bye how should and bye
1                       bye should
2                         good bye

还有另一个 csv,其中包含每个单词及其旁边的索引,如下所示:

     word  frequency  index
0     and        500     10
1     you        334      1
2     how        320      2
3  should        250      3
4     yes        100      4
5     bye         50      5
6    good          1      6

我正在尝试使用 Dictionary 作为我的问题的解决方案,但它只打印一个单词而不是整个句子的奇怪输出

import string
import pandas as pd
text=pd.read_csv("one.csv")

change=pd.read_csv("result.csv")
print(text)
update = dict(zip(change.word, change.index))
print(update)
text1 = text['sentences'].replace(update, regex=True)
print(text1)
text1.to_csv('yes.csv', header=False, index=False)

我希望输出是:

4 6 5 2 3 10 5

5 3

6 5

我得到的是这个输出:

我在做什么错任何解决方案?

【问题讨论】:

【参考方案1】:

您可以在拆分每一行后对所有项目使用带有series.get 的列表推导:

s=df2.set_index('word')['index']
final=df1.assign(index=[[s.get(a) for a in i.split()] for i in df1['sentences']])

                         sentences                   index
0  yes good bye how should and bye  [4, 6, 5, 2, 3, 10, 5]
1                       bye should                  [5, 3]
2                         good bye                  [6, 5]

【讨论】:

但这是打印句子以及如何让它只打印索引? 它打印一个列表你还好吗?如果您希望它们作为字符串检查@ansev answer 是的,我将列表转换回数据框以再次将其存储到 CSV 文件中,因为列表没有 to.csv 选项【参考方案2】:

我们可以用一个系列来代替, 另一方面,关键似乎是使用Series.astype 将系列转换为str:

text['index']=text.sentences.replace(change.set_index('word')['index']
                                           .astype(str),
                                     regex = True)
print(text)
#text.sentences.replace(change.set_index('word')['index'],regex = True)
#0    10
#1     3
#2     5
#Name: sentences, dtype: int64

输出

                         sentences           index
0  yes good bye how should and bye  4 6 5 2 3 10 5
1                       bye should             5 3
2                         good bye             6 5

【讨论】:

感谢您的回答,但您的正在将其转换为字符串,我会将这些数字输入神经网络,这可能会给我带来问题 那么@anky_91 解决方案会做得很好:)。如果您想摆脱列表,我们可以建议使用爆炸。 final.explode('index')。虽然如果列表不是障碍,增加行数可能是错误的 谢谢你的建议,我也会考虑爆炸

以上是关于使用python将句子中的每个单词替换为单词索引的主要内容,如果未能解决你的问题,请参考以下文章

将 pandas df 中的句子拆分为多行单词并对每个句子进行编号

如何编写一个函数,将句子中每个单词开头的所有辅音字符串转换为“r”,直到它变成元音?

如何让 Python 循环遍历句子,但它给了我句子中的单词而不是句子中的每个字母? [复制]

使用短语中的信息查找句子中单词的索引

根据每个句子的第一个单词将 pandas 数据框列中的字符串列表分解为新列

替换字符串中的特定单词(Python)