【问题标题】:Replace specific words in sentence by different names in python用python中的不同名称替换句子中的特定单词
【发布时间】:2017-07-11 11:52:26
【问题描述】:

我正在尝试将句子中的特定单词替换为不同的名称,每个单词都会有一个新名称。例如:

my_words = {[ 'a','b'],['c','d','e','f'], ['l','m','n']}
my_sentences = {' w0 w1 a w2 w3 b w4' , ' w0 w1 w2 c w3 d w4 e f' , 'w0 w1 w2 l m w3 w4 n w5']

我想替换(a,'first_word') 并替换第一句中的(b ,' second_word')。另外,我想替换(c,'first_word')(d, 'second_word'),列表中的其余单词(e,f)将在第二句中替换为'other_word'。 我编写了一个代码,将所有特定单词替换为'first_word'。看下面的代码:

def replace_all(sentences=[], words = []):
     text = []
     A_regex = re.compile('|'.join(map(re.escape, words)))
     for t in sentences:
         t = A_regex.sub("first_word", t)
         text.append(t)
    return text

我尝试了另一个代码:

for t in sentences:
    for w in words:
        for j in range (len(w)):
           t = t.replace(w[j][0],'FIRST_word')
           t = t.replace(w[j][1],'SECOND_word')
           if j == -1:
               break
           else:
              t = t.replace(w[j][2:-1],'OTHER_words')
     break

但它不起作用,

感谢您的帮助或任何提示。

【问题讨论】:

  • 你想要的输出是什么?
  • 输出必须是这样的: [' w0 w1 first_word w2 w3 second_word w4' , ' w0 w1 w2 first_word w3 second_word w4 other_word other_word' , 'w0 w1 w2 first_word second_word w3 w4 other_word w5']
  • 如果有重复怎么办?比如w0 a a w1,会是w0 first_word first_word w1吗?
  • 如果有重复的话,第一个单词会被替换,第二个单词会被忽略
  • @S.M 如果你的第一个项目是['b', 'a'],那么第一个对应的元素是w0 w1 second_word w2 w3 first_word w4 吗?

标签: python


【解决方案1】:

按照您的方法,您可以将其修复如下:

# You need to add spaces before and after each letter to avoid replacing letters in words.
my_words = [[' a ', ' b '], [' c ', ' d ', ' e ', ' f '], [' l ', ' m ', ' n ']]
my_sentences = ['w0 w1 a w2 w3 b w4', ' w0 w1 w2 c w3 d w4 e f', 'w0 w1 w2 l m w3 w4 n w5']
for i, c in enumerate(my_words):
    for j, word in enumerate(c):
        if j == 0:
            my_sentences[i] = my_sentences[i].replace(word, ' first_word ')
        elif j == 1:
            my_sentences[i] = my_sentences[i].replace(word, ' second_word ')
        else:
            my_sentences[i] = my_sentences[i].replace(word, ' other_word ')
print my_sentences

输出:

['w0 w1 first_word w2 w3 second_word w4', ' w0 w1 w2 first_word w3 second_word w4 other_word f', 'w0 w1 w2 first_word second_word w3 w4 other_word w5']

但是,我强烈建议您改用 dictionary 以提高效率。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-12
    • 2012-09-14
    • 1970-01-01
    • 2020-04-16
    相关资源
    最近更新 更多