列表和文本文件之间的精确字符串匹配

2024-10-01 13:43:33 发布

您现在位置:Python中文网/ 问答频道 /正文

ViolList是一个包含元素['a230kv'、'bcd120kv(after)'、'yz ckt1']的列表,txt文件有如下行

说明“BCD 120kv(之后)

第1行

说明A 230kv-fg 115kV ckt 2

第2行

说明yz ckt 1

第3行

描述

我需要完全匹配它们,这样一个230kv!=230kv-fg 115kV 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”:

The below image shows 'line' and 'x' but it still does not return Found


Tags: intrue元素foriflinecontentupper
1条回答
网友
1楼 · 发布于 2024-10-01 13:43:33

我认为您的问题是,文件行中有时有您看不到或不需要的空间。
这是一种猜测,但你可以尝试strip你的台词,你永远不知道。
因此,要做到这一点,只需替换这个:

if x.upper() == line.upper():

通过这个:

if x.upper() == line.upper().strip():

也可能是打字错误,但你写道:

outfile.write('Found") # choose one of the quotes

最后,我只想指出,对于实际的代码,如果您找到一个正确的行元素匹配,它将不断地为列表中的其余元素编写找到的代码,如果您不想,还可以添加:

sectionFound=False

在写入outfile或替换现有文件之后:

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')

希望对你有帮助

相关问题 更多 >