Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.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 在字典中搜索单词并返回行_Python_Csv - Fatal编程技术网

Python 在字典中搜索单词并返回行

Python 在字典中搜索单词并返回行,python,csv,Python,Csv,我正在尝试为一个程序创建一个搜索功能,该程序显示CSV文件中的公司信息。我正在使用csv.DictReader将文件内容放入字典,并将字典显示为数组。现在我在字典或数组中搜索单词并显示该单词所在的行时遇到问题。下面是CSV文件的一个小示例 CustomerID,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax ALFKI,Alfreds Futterkiste,Maria A

我正在尝试为一个程序创建一个搜索功能,该程序显示CSV文件中的公司信息。我正在使用csv.DictReader将文件内容放入字典,并将字典显示为数组。现在我在字典或数组中搜索单词并显示该单词所在的行时遇到问题。下面是CSV文件的一个小示例

CustomerID,CompanyName,ContactName,ContactTitle,Address,City,Region,PostalCode,Country,Phone,Fax
ALFKI,Alfreds Futterkiste,Maria Anders,Sales Representative,Obere Str. 57,Berlin,NULL,12209,Germany,030-0074321,030-0076545
AROUT,Around the Horn,Thomas Hardy,Sales Representative,120 Hanover Sq.,London,NULL,WA1 1DP,UK,(171) 555-7788,(171) 555-6750
我现在拥有的代码是用户输入,它是:

def search_company(data):
    word = input("Search for a company name: ")
我怎样才能得到这些结果

Search for a company name: Around the Horn

AROUT,Around the Horn,Thomas Hardy,Sales Representative,120 Hanover Sq.,London,NULL,WA1 1DP,UK,(171) 555-7788,(171) 555-6750
我试过这样做,但似乎只有当你只是从列表而不是字典中阅读时,这才有效

for i, row in enumerate(data):
            for j, column in enumerate(row):
                if word in column:
                    print(row)
简单解决方案:

import csv 

word = input("Search for a company name: ")

with open(csv_path) as csvfile:
    csvreader = csv.reader(csvfile, delimiter=',')

    for row in csvreader:
        if row[1] == word:
            print(row)
这应该起作用:

import csv
def search_company(data):
    word = input("Search for a company name: ")
    f=open(data)
    my_reader=csv.DictReader(f,delimiter=",")
    for row in my_reader:
        for entry in row:
            if row[entry]==word:
                print(row)
search_company("example.csv")

读取该文件应该是很好的第一步。我在您的代码中没有看到任何尝试这样做的内容,也没有在其中进行搜索。你现在得到的只是一个无用的提示。重新发明轮子。使用数据库/sql引擎谢谢!我非常专注于迭代数据,我没有想到仅仅从实际文件中读取数据。谢谢!同样,我专注于对数据进行迭代,我没有考虑从实际文件中读取数据。