繁体   English   中英

Python-从文本文件中删除单词或匹配字符串

[英]Python - remove a word or matching string from a text file

我正在尝试从文本文件中删除一个单词,并发现了似乎有效的代码。

但是,它不匹配确切的单词,而是删除所有匹配的字母。

fin = open("input.txt")
fout = open("output.txt", "w+")
delete_list = input('delete : ')
for line in fin:
    for word in delete_list:
        line = line.replace(word, '')
    fout.write(line)
fin.close()
fout.close()
print ('done')

input.txt中

http://www.google.co.ma
google.com.mm
https://google.mn
www.google.com.mt

尝试删除http://(仅)的结果如下-

output.txt的

www.google.co.ma
google.com.mm
sgoogle.mn
www.google.com.m

让我们看看这里发生了什么:

  1. 您调用input ,它返回一个字符串“ http://”。 您将此分配给变量delete_list
  2. 您可以使用for循环遍历delete_list 但请注意: delete_list是字符串,而不是列表。 当使用for循环遍历字符串时,它将循环遍历字符串的字母
  3. 您遍历每个字母并将其从行中删除。

您可以通过三件事来解决此问题:

  1. 将您的delete_list分配更改为一个单元素列表: delete_list = [input("word to delete: ")]

  2. 重命名delete_list以更准确地反映其真实值,例如word_to_delete ,然后不要使用for循环-只需直接执行line.replace(word_to_delete, '')

  3. 使用循环从用户那里获取单词列表

希望这能说明问题!

我刚刚开始编码,所以不知道这个解决方案看起来多么丑陋,但是重新模块似乎很好。

from re import sub
with open('test.txt') as f:
    file = f.read().split('\n')
for i in range(len(file)):
    file[i] = sub(r'http[s]?://', '', file[i])
#print(file)
with open('test1.txt', 'w') as f1:
    f1.writelines(["%s\n" % item  for item in file])

或者如果您不想使用re模块,则可以使用if语句代替

with open('test.txt') as f:
    file = f.read().split('\n')
for i in range(len(file)):
    if file[i].startswith('https://'):
        link = file[i]
        file[i] = link[8:]
    elif file[i].startswith('http://'):
        link = file[i]
        file[i] = link[7:]
#print(file)
with open('test1.txt', 'w') as f1:
    f1.writelines(["%s\n" % item  for item in file])

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM