简体   繁体   English

通过检查熊猫数据框来替换单词

[英]Replace words by checking from pandas dataframe

I have a data frame as below.我有一个如下的数据框。

ID  Word       Synonyms
------------------------
1   drove      drive
2   office     downtown
3   everyday   daily
4   day        daily
5   work       downtown

I'm reading a sentence and would like to replace words in that sentence with their synonyms as defined above.我正在阅读一个句子,并想用上面定义的同义词替换该句子中的单词。 Here is my code:这是我的代码:

import nltk
import pandas as pd
import string

sdf = pd.read_excel('C:\synonyms.xlsx')
sd = sdf.apply(lambda x: x.astype(str).str.lower())
words = 'i drove to office everyday in my car'

#######

def tokenize(text):
    text = ''.join([ch for ch in text if ch not in string.punctuation])
    tokens = nltk.word_tokenize(text)
    synonym = synonyms(tokens)
    return synonym

def synonyms(words):
    for word in words:
        if(sd[sd['Word'] == word].index.tolist()):
            idx = sd[sd['Word'] == word].index.tolist()
            word = sd.loc[idx]['Synonyms'].item()
        else:
            word
    return word

print(tokenize(words))

The code above tokenizes the input sentence.上面的代码标记了输入句子。 I would like to achieve the following output:我想实现以下输出:

In : i drove to office everyday in my cari drove to office everyday in my car
Out : i drive to downtown daily in my car外出i drive to downtown daily in my car

But the output I get is但我得到的输出是

Out : carcar

If I skip the synonyms function, then my output has no issues and is split into individual words.如果我跳过synonyms功能,那么我的输出就没有问题并且会被拆分为单个单词。 I am trying to understand what I'm doing wrong in the synonyms function.我试图了解我在synonyms功能中做错了什么。 Also, please advise if there is a better solution to this problem.另外,请告知是否有更好的解决方案来解决此问题。

I would take advantage of Pandas/NumPy indexing.我会利用 Pandas/NumPy 索引。 Since your synonym mapping is many-to-one, you can re-index using the Word column.由于您的同义词映射是多对一的,您可以使用Word列重新索引。

sd = sd.applymap(str.strip).applymap(str.lower).set_index('Word').Synonyms
print(sd)
Word
drove          drive
office      downtown
everyday       daily
day            daily
Name: Synonyms, dtype: object

Then, you can easily align a list of tokens to their respective synonyms.然后,您可以轻松地将标记列表与其各自的同义词对齐。

words = nltk.word_tokenize(u'i drove to office everyday in my car')
sentence = sd[words].reset_index()
print(sentence)
       Word  Synonyms
0         i       NaN
1     drove     drive
2        to       NaN
3    office  downtown
4  everyday     daily
5        in       NaN
6        my       NaN
7       car       NaN

Now, it remains to use the tokens from Synonyms , falling back to Word .现在,它仍然使用来自Synonyms的标记,回退到Word This can be achieved with这可以通过

sentence = sentence.Synonyms.fillna(sentence.Word)
print(sentence.values)
[u'i' 'drive' u'to' 'downtown' 'daily' u'in' u'my' u'car']
import re
import pandas as pd
sdf = pd.read_excel('C:\synonyms.xlsx')
rep = dict(zip(sdf.Word, sdf.Synonyms)) #convert into dictionary

words = "i drove to office everyday in my car"
rep = dict((re.escape(k), v) for k, v in rep.iteritems())
pattern = re.compile("|".join(rep.keys()))
rep = pattern.sub(lambda m: rep[re.escape(m.group(0))], words)

print rep

output输出

i drive to downtown daily in my car

Courtesy : https://stackoverflow.com/a/6117124/6626530礼貌: https : //stackoverflow.com/a/6117124/6626530

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM