[英]Remove a String Section from a file in python, with dynamic string matching?
[英]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
讓我們看看這里發生了什么:
input
,它返回一個字符串“ http://”。 您將此分配給變量delete_list
。 for
循環遍歷delete_list
。 但請注意: delete_list
是字符串,而不是列表。 當使用for
循環遍歷字符串時,它將循環遍歷字符串的字母 。 您可以通過三件事來解決此問題:
將您的delete_list
分配更改為一個單元素列表: delete_list = [input("word to delete: ")]
重命名delete_list
以更准確地反映其真實值,例如word_to_delete
,然后不要使用for
循環-只需直接執行line.replace(word_to_delete, '')
。
使用循環從用戶那里獲取單詞列表 。
希望這能說明問題!
我剛剛開始編碼,所以不知道這個解決方案看起來多么丑陋,但是重新模塊似乎很好。
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.