如何用Python查找和替换列表中的元素

2024-10-02 18:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个list{}的tuples和一些类似的数据:[('word1','sentence1'),('word2','sentence1'),('word3','sentence1') ...],我循环每个元组,得到每个单词和句子,如下所示:

for collection in tup:
        qword = collection[0]
        sentence = collection[1]

到目前为止,一切顺利。我需要删除句子中的每个单词,所以我这样做:

q_sentence_split = sentence.split()
new_sentence_split = [word.replace(q_word, '.....') for word in q_sentence_split]
new_sentence = ' '.join(sentence_split)

但是这并没有给我我所需要的,因为它从q_senetnce_split中的每个单词中删除元组的word字符,但我需要的只是单词,而不是将单词的字符与句子中每个单词的字符进行比较

我尝试将if放在for word in q_sentence_split后面,如下所示:

new_sentence_split = [word.replace(q_word, '.....') for word in q_sentence_split if word == qword]

但这只是删除了句子中的每个单词,所以我不知道我的代码有什么问题


Tags: innewforif字符单词sentencereplace
2条回答

试试这个:

lst = [('word1', 'The word1 is in this sentence'), ('word2', 'The word2blawblaw is in this sentence'),
       ('word3', 'The word1 is in this sentence')]

for word, sentence in lst:
    print(' '.join(i for i in sentence.split() if word not in i))

输出:

The is in this sentence
The is in this sentence
The word1 is in this sentence

我故意把word1放在第三句

说明:

首先我们迭代lst,它在每次迭代中给我们一个元组,我们用word, sentence解压它

在分割sentence之后,它成为一个列表,即['The', 'word1', 'is', 'in', 'this', 'sentence'](在第一次迭代中)

然后我们再次遍历这个列表,它给出了单个单词,我们所要做的就是检查我们的word是否在这些单词中。如果它不在那里,那就是我们想要的

最后我们做' '.join()来造句

以下是您可以做的:

list1 = [('word1', 'The word1 is in this sentence'), ('word2', 'The word2blawblaw is in this sentence'),
       ('word3', 'The word1 is in this sentence')]

for x, y in list1:
    print(' '.join(i for i in y.split() if word not in i))

相关问题 更多 >