我编写了一个函数来删除字符串中的某些单词和字符。使用文件将有问题的字符串读入程序。该程序可以正常工作,除非文件的任何位置在文件正文中的任何位置都包含以下内容。
安全启动的安全更新(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
文件的任何特定行,该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
)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句