简体   繁体   English

如何用另一个词替换文本中的某些词

[英]How to replace some words in a text with another word

I am trying to replace a word ie "sound system" with "sound_sytem" in python using dictionary.我正在尝试使用字典在 python 中用“sound_sytem”替换一个单词,即“声音系统”。 However it's not working.但是它不起作用。

Here is my code:这是我的代码:

dictionary = {'audio system': 'audio_system'}
def replace_word(text):
  return " ".join([dictionary.get(w,w) for w in text.split()])

text = "adding a little more to an audio system,improve the audio system to be better"

print(replace_word(text))

here is my output:这是我的 output:

adding a little more to an audio system,improve the audio system to be better

Try using replace() :尝试使用replace()

for i in dictionary:
    text.replace(i,dictionary[i])

this just replaces the key with value.这只是用值替换键。
Your code doesn't work because, split function by default splits by space and audio system is split as audio and system .您的代码不起作用,因为默认情况下拆分 function 按空间拆分,并且audio system拆分为audiosystem


Lets do this your way, using join:让我们按照自己的方式使用 join:

dictionary = {'audio system': 'audio_system'}
def replace_word(text):
  return [dictionary[j].join([text.split(i) for i in dictionary][0]) for j in dictionary][0]

text = "adding a little more to an audio system,improve the audio system to be better"

print(replace_word(text))

暂无
暂无

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

相关问题 如何用星号替换字符串中某些被禁词的字符? 禁止的单词存储在另一个文本文件中 - How to replace character of some banned word of a string with star? banned words are stored in another text file 在计算文本中单词准确性的频率时,如何忽略某些单词? - How to ignore some words when counting the frequency of a word accuracy in a text? 如何使用python替换文本文件中某些特定单词的字符 - How to replace a character in some specific word in a text file using python 如果文本列表和删除单词列表很大,如何处理从文本列表列表中删除某些单词 - How to deal with removing some words out of lists of text list if text list and remove word list are huge 如何替换单词,计数单词并保存计数 - How to replace words, count a word, and save the count 如何用单词网的同义词替换单词? - How to replace words with their synonyms of word-net? 如何忽略Python中词云中的某些单词? - How to ignore some words in a word cloud in Python? 如何仅用逗号前第一个出现的单词替换 dataframe 文本列 - How to replace dataframe text column with only the 1st occuring word / words before a comma 如何使用 Python 将文本文件中仅出现一次的单词替换为其他单词? - How do you replace the words that are only appearing once with other word within a text file using Python? 用另一个随机单词替换文本文件中 n% 的单词 - Replace n% of words in a text files with random words from another
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM