Python 列表和文本文件数据之间的精确字符串匹配
ViolList是一个包含元素['A230kV'、'BCD120kV(之后)'、'YZCKT1']的列表,txt文件中有如下行 说明“BCD 120kv(之后) 第1行 说明A 230kv-fg 115 kv电路2Python 列表和文本文件数据之间的精确字符串匹配,python,string-matching,Python,String Matching,ViolList是一个包含元素['A230kV'、'BCD120kV(之后)'、'YZCKT1']的列表,txt文件中有如下行 说明“BCD 120kv(之后) 第1行 说明A 230kv-fg 115 kv电路2 with open(ContFile.get(), "r") as content_file: sectionFound = False for line in content_file: for x in ViolList:
with open(ContFile.get(), "r") as content_file:
sectionFound = False
for line in content_file:
for x in ViolList:
x = 'description ' + x
if x.upper() == line.upper():
sectionFound = True
print sectionFound
break
if sectionFound == True:
outfile.write('Found")
第2行
说明yz ckt 1
第3行
描述
行
我需要精确匹配它们,以便230kv!=230kv-fg 115 kv ckt 2
with open(ContFile.get(), "r") as content_file:
sectionFound = False
for line in content_file:
for x in ViolList:
x = 'description ' + x
if x.upper() == line.upper():
sectionFound = True
print sectionFound
break
if sectionFound == True:
outfile.write('Found")
下图显示了“line”和“x”,但仍然没有返回Found:
我认为您的问题在于文件行中有时有您看不到或不需要的空间。
这是一种猜测,但你可以尝试你的台词,你永远不知道。
因此,要做到这一点,只需替换此项:
if x.upper() == line.upper():
if x.upper() == line.upper().strip():
通过这个:
if x.upper() == line.upper():
if x.upper() == line.upper().strip():
也可能是打字错误,但你写道:
outfile.write('Found") # choose one of the quotes
最后,我只想指出,对于实际代码,如果您找到一个正确的行元素匹配,它将不断地为其余的列表元素编写查找到的内容,如果您不希望,您还可以添加:
sectionFound=False
在写入输出文件后,或替换现有文件:
sectionFound=False
行内迭代,或:
break
如果不想继续检查列表中的其他元素
最后一件事的例子:
with open(ContFile, "r") as content_file:
for line in content_file:
sectionFound = False
for x in ViolList:
x = 'description ' + x
if x.upper() == line.upper().strip():
sectionFound = True
print sectionFound
break
if sectionFound == True:
outfile.write('Found')
希望对您有所帮助谢谢!成功了。我之前试过做这个条带,但是我将条带添加到了x.upper()和line.upper()。这就是为什么不起作用的原因吗?顺便说一句,一旦sectionFound为真,代码还有更多内容,只是为了写问题而将其缩短为打印@Rayhane MamaAlright您可以忽略我在最后一部分中所说的内容,但我将把它们放在那里,只是为了将来的用户提供文档。出于同样的目的,如果答案完全符合您的需要,请随意接受它;)是的,这可能是个问题,取决于你的名单@GigI