2

我有这段代码应该打开并读取两个文本文件,并在两个文本文件中都存在一个单词时匹配。匹配通过打印“SUCESS”并将单词写入 temp.txt 文件来表示。

dir = open('listac.txt','r')
path = open('paths.txt','r')
paths = path.readlines()
paths_size = len(paths)
matches = open('temp.txt','w')
dirs = dir.readlines()

for pline in range(0,len(paths)):
        for dline in range(0,len(dirs)):
                p = paths[pline].rstrip('\n').split(".")[0].replace(" ", "")
                dd = dirs[dline].rstrip('\n').replace(" ", "")
                #print p.lower()
                #print dd.lower()
                if (p.lower() == dd.lower()):
                        print "SUCCESS\n"
                        matches.write(str(p).lower() + '\n')

listac.txt 被格式化为

/teetetet
/eteasdsa
/asdasdfsa
/asdsafads
.
. 
...etc

path.txt 格式为

/asdadasd.php/asdadas/asdad/asd
/adadad.html/asdadals/asdsa/asd
.
.
...etc

因此,我使用 split 函数来获取点之前的第一个 /asadasda(在 paths.txt 中)。问题是这些词似乎永远不会匹配,我什至在每个 IF 语句之前打印出每个比较并且它们是相等的,Python 在比较字符串之前还有其他事情吗?

=======

感谢大家的帮助。正如你所建议的,我清理了代码,所以它最终是这样的:

dir = open('listac.txt','r')
path = open('paths.txt','r')
#paths = path.readlines()
#paths_size = len(paths)

for line in path:
        p = line.rstrip().split(".")[0].replace(" ", "")
        for lines in dir:
                d = str(lines.rstrip())
                if p == d:
                        print p + " = " + d

显然,在进入第二个 for 循环之前声明和初始化 p 会对以后的比较产生影响。当我在第二个 for 循环中声明 p 和 d 时,它不起作用。我不知道原因,但如果有人这样做,我正在听:)

再次感谢!

4

2 回答 2

7

当我们将整个数据文件读入内存时,为什么不尝试使用sets并获取交集呢?:

def format_data(x):
    return x.rstrip().replace(' ','').split('.')[0].lower()

with open('listac.txt') as dirFile:
     dirStuff = set( format_data(dline) for dline in dirFile )

with open('paths.txt') as pathFile:
     intersection = dirStuff.intersection( format_data(pline) for pline in pathFile )

for elem in intersection:
    print "SUCCESS\n"
    matches.write(str(elem)+"\n")

format_data对两个数据集使用了相同的函数,因为它们看起来或多或少相同,但如果你愿意,你可以使用多个函数。另请注意,此解决方案仅将两个文件中的 1 个文件读入内存。与对方的交点应该懒惰地计算。

正如评论中所指出的,这并没有试图保留订单。但是,如果您确实需要保留订单,请尝试以下操作:

<snip>
...
</snip>

with open('paths.txt') as pathFile:
    for line in pathFile:
        if format_line(line) in dirStuff:
           print "SUCCESS\n"
           #...
于 2012-09-11T14:55:57.450 回答
4

我必须查看更多您的数据集才能了解您为什么没有得到匹配。我已将您的一些代码重构为更加pythonic

dirFile = open('listac.txt','r')
pathFile = open('paths.txt','r')
paths = pathFile.readlines()
dirs = dirFile.readlines()

matches = open('temp.txt','w')

for pline in paths:
    p = pline.rstrip('\n').split(".")[0].replace(" ", "")
    for dline in dirs:
        dd = dline.rstrip('\n').replace(" ", "")
        #print p.lower()
        #print dd.lower()
        if p.lower() == dd.lower():
            print "SUCCESS\n"
            matches.write(str(p).lower() + '\n')
于 2012-09-11T14:50:32.757 回答