我有这个代码应该打开并阅读两个文本文件,并匹配两个字中都存在的字。通过打印“SUCESS”并将该单词写入temp.txt文件来表示匹配。作为无法比较Python中的字符串
/teetetet
/eteasdsa
/asdasdfsa
/asdsafads
.
.
...etc
paths.txt被格式化为
/asdadasd.php/asdadas/asdad/asd
/adadad.html/asdadals/asdsa/asd
.
.
...etc
因此我使用分割功能,以获得第一/ asadasda(路径内
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被格式化.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
显然,具有p申报并进入第二个for循环之前进行初始化,使在比较的道路的差异。当我在第二个for循环中声明p和d时,它不起作用。我不知道原因,但如果有人这样做,我在听:)
再次感谢!
在您的示例中,没有匹配。 –
太复杂了。不要在'range(0,len(paths))'中使用'''''''',只要用''''''''''''''''<!为什么'rstrip('\ n')'。可能有一个额外的'\ r'。只需使用'rstrip()'。 – Matthias
您也可以将'p = ...'移动到inner for循环之外,因为它每次都执行相同的计算。 – mgilson