[英]How to find most frequent string value in a csv column and return it? (Python)
[英]Python - Searching for a value in CSV column and return string
我是Python的新手,正在从事一个简单的项目,该项目的一部分应该搜索用户定义的变量,如果找到,则根据找到的行返回一个字符串。
我读过许多文章,将我带到已有的代码,但是运行后,虽然我没有收到任何错误,但代码继续进行下一部分。 在这种情况下,我省略了以下部分,但是如果单独运行,则会在输入变量之后中断。
import csv #CSV File Handling
#Define variables for customer file reading and appending
custData = open('custData.csv', 'a+')
custFields = ['ContactLast','ContactFirst','Company','Credit','Phone','Address','City','State','Zip']
reader = csv.DictReader(custData, delimiter=',')
writer = csv.DictWriter(custData, fieldnames=custFields)
search = ''
#Open the file
with custData:
#Display the Welcome Message and Main Menu
mainmenugo = 'Y'
while (mainmenugo.upper() == 'Y'):
print ('-------------------- What would you like to do? ------------------\n'
'--- (1) Lookup Account (2) New Account (quit) Shutdown ---\n'
'------------------------------------------------------------------')
mainmenugo = 'n' #Stop the loop from itirating forever on start
mainmenuselect = input('Type your selection and press return : ')
if mainmenuselect == '1': ## Account Options Mode
search = input('Enter the contact last name to search : ')
for row in reader:
if search == row['ContactLast']:
print (row['Company'], 'has a balance of $', row['Credit'], '. What would you like to do?')
为了清楚起见,省略了部分代码,但这就是为什么我可以按原样设置它,尽管我确信有更简单的方法来处理它。 我尝试了几种不同的方法,但是我真的不确定从哪里开始,因为我遇到的错误很少,但是没有输出。 谢谢!
我认为您遇到以下问题。 Python 3中的input()
会有效评估用户输入,将用户输入1转换为整数1
,然后您尝试将其与字符串'1'
进行比较。
换句话说,这是正在发生的事情:
In [1]: search = input('Enter the contact last name to search : ')
Enter the contact last name to search : 1
In [2]: type(search)
Out[2]: int
In [3]: search == '1'
Out[3]: False
在您的情况下,如果用户键入1
,则if mainmenuselect == '1':
比较将是虚假的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.