[英]Python cannot read a file which contains a specific string
我編寫了一個函數來刪除字符串中的某些單詞和字符。 使用文件將有問題的字符串讀入程序。 該程序可以正常工作,除非文件的任何位置在文件正文中的任何位置包含以下內容。
安全啟動的安全更新(3177404)此安全更新解決了Microsoft Windows中的漏洞。 如果攻擊者在目標設備上安裝了受影響的策略,則該漏洞可能允許繞過安全啟動安全功能。 攻擊者必須具有管理特權或物理訪問權限才能安裝策略並繞過安全啟動。
我從未經歷過這種奇怪的行為。 有人有什么建議嗎?
這是我編寫的功能。
def scrub(file_name):
try:
file = open(file_name,"r")
unscrubbed_string = file.read()
file.close()
cms = open("common_misspellings.csv","r")
for line in cms:
replacement = line.strip('\n').split(',')
while replacement[0] in unscrubbed_string:
unscrubbed_string = unscrubbed_string.replace(replacement[0],replacement[1])
cms.close()
special_chars = ['.',',',';',"'","\""]
for char in special_chars:
while char in unscrubbed_string:
unscrubbed_string = unscrubbed_string.replace(char,"")
unscrubbed_list = unscrubbed_string.split()
noise = open("noise.txt","r")
noise_list = []
for word in noise:
noise_list.append(word.strip('\n'))
noise.close()
for noise in noise_list:
while noise in unscrubbed_list:
unscrubbed_list.remove(noise)
return unscrubbed_list
except:
print("""[*] File not found.""")
您的代碼可能正在掛起,因為您的.replace()
調用處於while
循環中。 如果對於.csv
文件的任何特定行, .csv
replacement[0]
字符串是其對應的replacement[1]
的子字符串 ,並且如果其中任何一個出現在關鍵文本中,則while
循環將永遠不會結束。 實際上,您根本不需要while
循環-單個.replace()
調用將替換所有出現的事件。
但這只是您使用一攬子unscrubbed_string.replace(...)
當前方法所遇到的問題的一個示例,您將需要使用正則表達式替換(來自re
)模塊,或者分解您的字符串自己說出來,然后逐字逐句地工作。 為什么? 好吧,這是一個簡單的示例: 'Teh'
需要更正為'The'
但是如果文檔中包含對'Tehran'
的引用怎么辦? 您的“安全啟動”文本將包含與此類似的示例。
如果使用正則表達式,符號\\b
可以通過匹配任何類型的單詞邊界(字符串的開頭或結尾,空格,標點符號)來解決此問題。 這是一個簡化的示例:
import re
replacements = {
'Teh':'The',
}
unscrubbed = 'Teh capital of Iran is Tehran. Teh capital of France is Paris.'
better = unscrubbed
naive = unscrubbed
for target, replacement in replacements.items():
naive = naive.replace(target, replacement)
pattern = r'\b' + target + r'\b'
better = re.sub(pattern, replacement, better)
print(unscrubbed)
print(naive)
print(better)
輸出,強調錯誤:
伊朗德資本是德黑蘭。 法國的德資本是巴黎。 (未
unscrubbed
)伊朗的首都是Theran 。 法國的首都是巴黎。 (
naive
)伊朗的首都是德黑蘭。 法國的首都是巴黎。 (
better
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.