Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python嵌套for循环以将文本文件中的字符串与csv文件中的字符串相匹配_Python_Python 2.7_Csv_Nested Loops - Fatal编程技术网

Python嵌套for循环以将文本文件中的字符串与csv文件中的字符串相匹配

Python嵌套for循环以将文本文件中的字符串与csv文件中的字符串相匹配,python,python-2.7,csv,nested-loops,Python,Python 2.7,Csv,Nested Loops,我的代码的目的是读取文本文件,将行添加到数组中,迭代数组中的每个元素,将元素转换为字符串,并从csv文件返回包含此字符串的行。我的代码是: #Read cvs File from url import csv import urllib2 url = 'mycsvfile.csv' response = urllib2.urlopen(url) cr = csv.reader(response) #Read txt File import linecache fileName = 'my

我的代码的目的是读取文本文件,将行添加到数组中,迭代数组中的每个元素,将元素转换为字符串,并从csv文件返回包含此字符串的行。我的代码是:

#Read cvs File from url
import csv
import urllib2   
url = 'mycsvfile.csv'
response = urllib2.urlopen(url)
cr = csv.reader(response)

#Read txt File
import linecache
fileName = 'myfile.txt'
myFile = open(fileName,'r')
list_of_lists = []
try:
    for line in myFile:
        list_of_lists.append(line.strip())

    #Lookup Lines
    for element in list_of_lists:
        elementstring=''.join(element)
        for row in cr:
            if elementstring in row:
                print row


finally:
    myFile.close()

代码没有显示任何内容。

我的猜测是,在csv读取器的第一次迭代中,您没有满足条件的任何行-
如果行中的elementstring:
(对于第一个
elementstring
)。在这个迭代之后,您已经耗尽了您的csv,并且它已经到达了末尾,尝试再次迭代它是不起作用的

尝试在循环外部打开url和csv,并将每个内部行转换为一个集合,然后将它们全部添加到列表中,然后使用该列表进行循环-

#Read cvs File from url
import csv
import urllib2   
url = 'mycsvfile.csv'
response = urllib2.urlopen(url)
cr = csv.reader(response)
csvset = [set(i) for i in cr]

#Read txt File
import linecache
fileName = 'myfile.txt'
myFile = open(fileName,'r')
list_of_lists = []
try:
    for line in myFile:
        list_of_lists.append(line.strip())

    #Lookup Lines
    for element in list_of_lists:
        elementstring=''.join(element)
        for row in csvset:
            if elementstring in row:
                print row


finally:
    myFile.close()

我看不出有什么明显的问题。为什么不添加一些
print repr(elementstring)
print repr(row)
来查看元素是否匹配?顺便说一句,你的
列表中的列表将不包含列表,而只包含字符串,因此
''。join
是毫无意义的。还有,为什么要创建列表的列表,而不是直接迭代文件呢?我同意@tobias_k的观点,并想补充一点:您使用过Python调试器吗?调试器使您能够逐行检查代码,并在每一步中查看所有变量。这是了解代码真正在做什么的一个很好的方法,因此您不必说“它不工作,我也不知道为什么。”我写过。@tobias_k我尝试过用elementstring='ExistingStringInFile'替换'elementstring='.join(element)',它确实找到了字符串并显示了所有数据。是的,这可能是问题所在!但是,我建议将文本文件中的行添加到集合中(如果不是太多),在外部循环中迭代CSV文件,并在该集合的CSV行中查找元素。可能会快一点。@tobias_k我也会尝试你上面的建议,因为获取数据有点慢。@user2842033我在回答中添加了集合的使用,请尝试一下。@AnandSKumar是的,它起作用了。非常感谢你们的帮助。非常感谢。@user2842033请记住接受答案(通过单击左侧的勾号),这将对社区有所帮助。