【问题标题】:Exact string matching between list and text file data列表和文本文件数据之间的精确字符串匹配
【发布时间】:2017-07-05 18:25:58
【问题描述】:

ViolList 是一个包含元素 ['A 230kv','BCD 120kv (after)','yz ckt 1'] 的列表,并且 txt 文件有诸如

之类的行

描述'BCD 120kv(后)

第一行

描述 A 230kv - fg 115 kv ckt 2

第 2 行

说明 yz ckt 1

第 3 行

描述...

行...

我需要完全匹配它们,使得 A 230kv != A 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:

【问题讨论】:

    标签: python string-matching


    【解决方案1】:

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

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

    这个:

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

    也可能是错字,但您写道:

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

    最后我只想指出,在实际代码中,如果您找到正确的行元素匹配,它将不断为其余的列表元素写入 Found,如果您不希望这样,您也可以添加:

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

    希望对你有帮助

    【讨论】:

    • 谢谢!那行得通。我之前试过做条带,但我把条带添加到 x.upper() 和 line.upper() 中。这就是为什么那行不通吗?顺便说一句,一旦 sectionFound 为真,代码还有更多内容,只是为了编写问题而将其缩短以打印。 @Rayhane 妈妈
    • 好吧,您可以忽略我在最后部分中所说的内容,但我会将它们留在那里,仅供将来用户使用。出于同样的目的,如果答案完全符合您的需求,请随时接受;)是的,这可能是个问题,取决于您的列表@GigI
    猜你喜欢
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 2022-11-03
    • 2022-09-26
    • 2021-10-18
    相关资源
    最近更新 更多