Python 将列表中的元素替换为空白
是否可以检查列表中的元素?如果它与“test01.txt”中的单词相同,则替换为空格 test01.txt:Python 将列表中的元素替换为空白,python,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,
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
“打印ssx”的结果:
如何替换ssx中的元素
预期结果:
['wow']
['listens', ' ', ' ', 'music']
[' ', 'good']
[' ', 'film', ' ', 'stunt', 'scheduling', 'i', 'think']
['really', 'enjoyed']
有什么建议吗?使用列表理解;首先将单词存储在一个集合中,以便更快地进行测试:
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
使用列表理解;首先将单词存储在一个集合中,以便更快地进行测试:
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
简单的解决方案是:
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
不仅仅是几个单词,您可能希望将其转换为集合
,以加快查找速度
因此,把所有这些放在一起:
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
简单的解决方案是:
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
不仅仅是几个单词,您可能希望将其转换为集合
,以加快查找速度
因此,把所有这些放在一起:
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