我想搜索CSV文件并打印True
或False
,这取决于我是否找到了字符串。但是,我遇到了一个问题,即如果它发现字符串嵌入在一个更大的文本字符串中,它将返回误报。例如:如果字符串是foo
,并且术语foobar
在CSV文件中,它将返回True
。我需要能够返回精确匹配。
username = input()
if username in open('Users.csv').read():
print("True")
else:
print("False")
我已经研究过使用mmap
、re
和csv
模块函数,但是我还没有任何进展。
编辑:这里有一个替代方法:
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)
6条答案
按热度按时间zz2j4svz1#
当你使用
csv
模块查看csv文件时,它会将每一行返回为一个列的列表,所以如果你想查找你的字符串,你应该修改你的代码如下:但由于它是csv文件,您可能希望用户名位于给定列:
omjgkv6w2#
你应该看看python中的csv模块。
它假定分隔符为逗号(替换为分隔符。请注意,必须事先定义用户名。还要更改文件名。代码循环遍历CSV文件中的所有行。row返回包含行中每个元素的字符串列表。例如,如果CSV文件中包含以下内容:
Joe,Peter,Michel
行将为['Joe', 'Peter', 'Michel']
。然后您可以检查您的用户名是否在该列表中。vs91vp4v3#
我已经使用了顶部的评论,它的工作和看起来不错,但它对我来说太慢了。
我有很多字符串的数组,我想检查它们是否在一个大的csv文件中。没有其他要求。
为此,我使用了(简化后,我迭代了一个数组字符串,并做了打印以外的其他工作):
连同:
我的时间减少了大约90%。代码锁很难看,但我很关心速度。有时候。
krcsximq4#
xsuvu9jc5#
扩展算法:
正如我可以在我的csv一些值与空间:",atleft,atright,both",我将 * zmo * 的代码打补丁如下
没关系谢谢。
旧时尚算法
我以前编写过一个"老式"算法,它可以处理任何允许的分隔符(这里是逗号、空格和换行符),所以我很好奇地比较了一下性能。
在一个非常简单的csv文件上有10000发子弹,我得到了:
在1.931804895401001秒内完成。
在1.926626205444336秒内完成。
由于这不是太坏,0.25%长,我认为这个好的老手做的算法可以帮助一些人(并将是有用的,如果更多的寄生字符作为条带只为空间)
这个算法使用bytes,可以用于字符串以外的任何对象。
它通过检查必须在允许的分隔符中的左右字节来搜索未嵌入到另一个名称中的名称。
它主要使用通过break或continue快速弹出的循环。
待检查:
searchUserName('pirla','test.csv')
与其他答案一样,代码在第一次匹配时退出,但可以很容易地扩展到查找所有匹配项。
高温加热
42fyovps6#