1

我正在尝试编写一个 python 代码来匹配 python 中两个列表中的内容。

一个制表符分隔的文件如下所示:

COPB2

KLMND7

BLCA8

如果你愿意的话,另一个文件 2 有一长串看起来相似的“名字”。文件中应该有一些相同的匹配项,我已成功识别并写入新文件。问题是当“名称”之一的末尾有其他字符时。例如,COPB2从上面应该匹配COPB2Afile2,但它不匹配。同样KLMND7应该匹配KLMND79。我应该使用正则表达式吗?把它们变成字符串?任何想法都有帮助,谢谢!

在下面看到的第一个响应之后,我到目前为止所做的工作:

with open(in_file1, "r") as names:
for line in names:
    file1_list = [i.strip() for i in line.split()]
    file1_str = str(file1_list)

with open(in_file2, "r") as symbols:
for line in symbols:
    items = line.split("\t")
    items = str(items)
    matches = items.startswith(file1_str)
    print matches

False当我知道应该有一些匹配时,此代码会返回。

4

3 回答 3

2

string.startswith()不需要正则表达式,如果它只是尾随字符

>>> g = "COPB2A"
>>> f = "COPB2"
>>> g.startswith(f)
True

这是一段工作代码:

file1_list = []
with open(in_file1, "r") as names:
    for line in names:
        line_items = line.split()
        for item in line_items:
            file1_list.append(item)

matches = []
with open(in_file2, "r") as symbols:
    for line in symbols:
        file2_items = line.split()
        for file2_item in file2_items:
            for file1_item in file1_list:
                if file2_item.startswith(file1_item):
                    matches.append(file2_item)
                    print file2_item
print matches

大文件可能会很慢。如果无法接受,我可以尝试考虑如何优化它。

于 2013-01-22T22:36:37.523 回答
0

如果您需要更通用的解决方案,您可以查看 difflib。请记住,这是一个很大的导入,开销很大,所以只有在你真的需要时才使用它。这是另一个有点相似的问题。

https://stackoverflow.com/questions/1209800/difference-between-two-strings-in-python-php

于 2013-01-22T22:48:00.913 回答
0

假设您将文件加载到列表 X、Y 中。

## match if a or b is equal to or substring of one another in a case-sensitive way
def Match( a, b):
    return a.find(b[0:min(len(a),len(b))-1])

common_words = {};
for a in X:
    common_words[a]=[];
    for b in Y:
        if ( Match( a, b ) ):
             common_words[a].append(b);

如果要使用正则表达式进行匹配,则要使用“单词匹配开头”运算符“^”。

import re
def MatchRe( a, b ):        
    # make sure longer string is in 'a'.
    if ( len(a) < len(b) ):
         a, b = b, a;
    exp = "^"+b;
    q = re.match(exp,a);
    if ( not q ):
       return False; #no match
    return True; #access q.group(0) for matches
于 2013-01-22T22:55:05.627 回答