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

replacing each words in sentence into the words index using python

我有两个 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

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

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

我得到的是这个输出:

我做错了什么有什么解决办法吗?

拆分每一行后,您可以对所有项目使用 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]

我们可以用一个系列来代替, 另一方面,密钥似乎将 Series 转换为 str with Series.astype:

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