用空格替换列表中的元素

时间:2013-01-06 12:35:54

标签: python

是否可以检查列表元素?如果它与“test01.txt”中的单词相同,则用空格替换?

test01.txt:

to
her
too
a
for

在代码中:

with open('C:/test01.txt') as words:
    ws = words.read().splitlines()
with open('C:/test02.txt') as file_modify4:
    for x in file_modify4:
        sx = map(str.strip, x.split("\t"))
        ssx = sx[0].split(" ")
        print ssx

“print ssx”的结果:

['wow']
['listens', 'to', 'her', 'music']
['too', 'good']
['a', 'film', 'for', 'stunt', 'scheduling', 'i', 'think']
['really', 'enjoyed']

如何替换ssx中的元素?

预期结果:

['wow']
['listens', ' ', ' ', 'music']
[' ', 'good']
[' ', 'film', ' ', 'stunt', 'scheduling', 'i', 'think']
['really', 'enjoyed']

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

使用列表推导;首先将单词存储在一组中以便更快地进行测试:

ws = set(ws)

# ...
    ssx = [w if w not in ws else ' ' for w in ssx]    

或者,作为一个完整的解决方案:

with open('C:/test01.txt') as words:
    ws = set(words.read().splitlines())

with open('C:/test02.txt') as file_modify4:
    for x in file_modify4:
        ssx = [w if w not in ws else ' ' for w in x.strip().split('\t')[0].split()]
        print ssx

答案 1 :(得分:1)

天真的解决方案是:

new_ssx = []
for word in ssx:
    if word in ws:
        new_ssx.append(' ')
    else:
        new_ssx.append(word)

当然,每当你有一个你只是在循环中追加的空列表时,你可以把它变成一个列表理解:

new_ssx = [' ' if word in ws else word for word in ssx]

如果ws超过几个字,您可能希望将其变为set以使查找更快。

所以,把它们放在一起:

with open('C:/test01.txt') as words:
    ws = set(words.read().splitlines())
with open('C:/test02.txt') as file_modify4:
    for x in file_modify4:
        sx = map(str.strip, x.split("\t"))
        ssx = sx[0].split(" ")
        new_ssx = [' ' if word in ws else word for word in ssx]
        print new_ssx