Python 检查字符串是否在 CSV 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17308872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check whether string is in CSV
提问by jars121
I want to search a CSV file and print either True
or False
, depending on whether or not I found the string. However, I'm running into the problem whereby it will return a false positive if it finds the string embedded in a larger string of text. E.g.: It will return True
if string is foo
and the term foobar
is in the CSV file. I need to be able to return exact matches.
我想搜索一个 CSV 文件并打印True
或False
,这取决于我是否找到了该字符串。但是,我遇到了一个问题,如果它找到嵌入在较大文本字符串中的字符串,它将返回误报。例如:True
如果字符串是foo
并且术语foobar
在 CSV 文件中,它将返回。我需要能够返回完全匹配。
username = input()
if username in open('Users.csv').read():
print("True")
else:
print("False")
I've looked at using mmap
, re
and csv
module functions, but I haven't got anywhere with them.
我已经研究过 using mmap
,re
和csv
module 函数,但我对它们一无所知。
EDIT: Here is an alternative method:
编辑:这是另一种方法:
import re
import csv
username = input()
with open('Users.csv', 'rt') as f:
reader = csv.reader(f)
for row in reader:
re.search(r'\bNOTSUREHERE\b', username)
采纳答案by zmo
when you look inside a csv file using the csv
module, it will return each row as a list of columns. So if you want to lookup your string, you should modify your code as such:
当您使用该csv
模块查看 csv 文件时,它将以列列表的形式返回每一行。所以如果你想查找你的字符串,你应该修改你的代码:
import csv
username = input()
with open('Users.csv', 'rt') as f:
reader = csv.reader(f, delimiter=',') # good point by @paco
for row in reader:
for field in row:
if field == username:
print "is in file"
but as it is a csv file, you might expect the username to be at a given column:
但由于它是一个 csv 文件,您可能希望用户名位于给定的列中:
with open('Users.csv', 'rt') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
if username == row[2]: # if the username shall be on column 3 (-> index 2)
print "is in file"
回答by Paco
You should have a look at the csv module in python.
你应该看看 python 中的 csv 模块。
is_in_file = False
with open('my_file.csv', 'rb') as csvfile:
my_content = csv.reader(csvfile, delimiter=',')
for row in my_content:
if username in row:
is_in_file = True
print is_in_file
It assumes that your delimiter is a comma (replace with the your delimiter. Note that username must be defined previously. Also change the name of the file.
The code loops through all the lines in the CSV file. row a list of string containing each element of your row. For example, if you have this in your CSV file: Joe,Peter,Michel
the row will be ['Joe', 'Peter', 'Michel']
. Then you can check if your username is in that list.
它假定您的分隔符是一个逗号(替换为您的分隔符。请注意,必须事先定义用户名。还要更改文件的名称。代码循环遍历 CSV 文件中的所有行。行包含每个字符串的列表您行的元素。例如,如果您的 CSV 文件中有这个:Joe,Peter,Michel
该行将是['Joe', 'Peter', 'Michel']
。然后您可以检查您的用户名是否在该列表中。
回答by OllieTaiani
import csv
scoresList=[]
with open ("playerScores_v2.txt") as csvfile:
scores=csv.reader(csvfile, delimiter= ",")
for row in scores:
scoresList.append(row)
playername=input("Enter the player name you would like the score for:")
print("{0:40} {1:10} {2:10}".format("Name","Level","Score"))
for i in range(0,len(scoresList)):
print("{0:40} {1:10} {2:10}".format(scoresList[i] [0],scoresList[i] [1], scoresList[i] [2]))
回答by akD
#!/usr/bin/python
import csv
with open('my.csv', 'r') as f:
lines = f.readlines()
cnt = 0
for entry in lines:
if 'foo' in entry:
cnt += 1
print"No of foo entry Count :".ljust(20, '.'), cnt