簡體   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