首字母缩略词替换为it';使用python调用s值
我有这样的字典,我需要用字典中的值替换文本中的首字母缩略词。我使用这段代码,但当我使用首字母缩略词替换为it';使用python调用s值,python,twitter,sentiment-analysis,Python,Twitter,Sentiment Analysis,我有这样的字典,我需要用字典中的值替换文本中的首字母缩略词。我使用这段代码,但当我使用首字母缩略词(“我们是gr8和awsm”)测试函数时,它并没有给我适当的结果。它应该告诉我我们很棒 def acronyms(text): my_dict = {} with open('acronym.txt') as fileobj: for line in fileobj: key, value = line.split('\t')
首字母缩略词(“我们是gr8和awsm”)测试函数时,它并没有给我适当的结果。
它应该告诉我我们很棒
def acronyms(text):
my_dict = {}
with open('acronym.txt') as fileobj:
for line in fileobj:
key, value = line.split('\t')
my_dict[key] = value
acronym_words = []
words = word_tokenize(text)
for word in words:
for candidate_replacement in my_dict:
if candidate_replacement in word:
word = word.replace(candidate_replacement, my_dict[candidate_replacement])
acronym_words.append(word)
acronym_sentence = " ".join(acronym_words)
return acronym_sentence
您可以使用
split
将句子拆分为单个单词,然后使用简单的列表理解替换所需的值:
dct = {'gr8': 'great', 'awsm': 'awesome'}
s = "we are gr8 and awsm"
def acronym(s, dct):
return ' '.join([dct.get(i, i) for i in s.split()])
print(acronym(s, dct))
输出:
we are great and awesome
您可以使用
split
将句子拆分为单个单词,然后使用简单的列表理解替换所需的值:
dct = {'gr8': 'great', 'awsm': 'awesome'}
s = "we are gr8 and awsm"
def acronym(s, dct):
return ' '.join([dct.get(i, i) for i in s.split()])
print(acronym(s, dct))
输出:
we are great and awesome
或者类似于:
re.sub(r'\b({})\b'.format('|'.join(dct)),lambda m:dct[m.group(0)],s)
或者类似于:re.sub(r'\b({})\b'.format('|'.join(dct)),lambda m:dct[m.group(0)],s)