检查字符串是否为CSV格式

2nc8po8w  于 2022-12-15  发布在  其他
关注(0)|答案(6)|浏览(171)

我想搜索CSV文件并打印TrueFalse,这取决于我是否找到了字符串。但是,我遇到了一个问题,即如果它发现字符串嵌入在一个更大的文本字符串中,它将返回误报。例如:如果字符串是foo,并且术语foobar在CSV文件中,它将返回True。我需要能够返回精确匹配。

username = input()

if username in open('Users.csv').read():
    print("True")
else:
    print("False")

我已经研究过使用mmaprecsv模块函数,但是我还没有任何进展。
编辑:这里有一个替代方法:

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)
zz2j4svz

zz2j4svz1#

当你使用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"

但由于它是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"
omjgkv6w

omjgkv6w2#

你应该看看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

它假定分隔符为逗号(替换为分隔符。请注意,必须事先定义用户名。还要更改文件名。代码循环遍历CSV文件中的所有行。row返回包含行中每个元素的字符串列表。例如,如果CSV文件中包含以下内容:Joe,Peter,Michel行将为['Joe', 'Peter', 'Michel']。然后您可以检查您的用户名是否在该列表中。

vs91vp4v

vs91vp4v3#

我已经使用了顶部的评论,它的工作和看起来不错,但它对我来说太慢了。
我有很多字符串的数组,我想检查它们是否在一个大的csv文件中。没有其他要求。
为此,我使用了(简化后,我迭代了一个数组字符串,并做了打印以外的其他工作):

with open('my_csv.csv', 'rt') as c:
    str_arr_csv = c.readlines()

连同:

if str(my_str) in str(str_arr_csv):
    print("True")

我的时间减少了大约90%。代码锁很难看,但我很关心速度。有时候。

krcsximq

krcsximq4#

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]))
xsuvu9jc

xsuvu9jc5#

扩展算法:
正如我可以在我的csv一些值与空间:",atleft,atright,both",我将 * zmo * 的代码打补丁如下

if field.strip() == username:

没关系谢谢。
旧时尚算法
我以前编写过一个"老式"算法,它可以处理任何允许的分隔符(这里是逗号、空格和换行符),所以我很好奇地比较了一下性能。
在一个非常简单的csv文件上有10000发子弹,我得到了:


在1.931804895401001秒内完成。

  • ---------------带有csv的算法2-------------
    在1.926626205444336秒内完成。
    由于这不是太坏,0.25%长,我认为这个好的老手做的算法可以帮助一些人(并将是有用的,如果更多的寄生字符作为条带只为空间)
    这个算法使用bytes,可以用于字符串以外的任何对象。
    它通过检查必须在允许的分隔符中的左右字节来搜索未嵌入到另一个名称中的名称。
    它主要使用通过break或continue快速弹出的循环。
def separatorsNok(x):
    return (x!=44) and (x!=32) and (x!=10) and (x!=13) #comma space lf cr

# set as a function to be able to run several chained tests 
def searchUserName(userName, fileName):

    # read file as binary (supposed to be utf-8 as userName)
    f = open(fileName, 'rb')
    contents = f.read()
    lenOfFile = len(contents)   

    
    # set username in bytes 
    userBytes = bytearray(userName.encode('utf-8'))
    lenOfUser = len(userBytes)
    posInFile = 0
    posInUser = 0

    while posInFile < lenOfFile:
        found = False
        posInUser = 0

        # search full name
        while posInFile < lenOfFile:
            if (contents[posInFile] == userBytes[posInUser]):
                posInUser += 1
                if (posInUser == lenOfUser):
                    found = True
                    break
            posInFile += 1
        if not found:
            continue

        # found a fulll name, check if isolated on left and on right
        # left ok at very beginning or space or comma or new line 
        if (posInFile > lenOfUser):
            if separatorsNok(contents[posInFile-lenOfUser]): #previousLeft
                continue
        # right ok at very end or space or comma or new line 
        if (posInFile < lenOfFile-1):
            if separatorsNok(contents[posInFile+1]):  # nextRight
                continue
        # found and bordered
        break
    # main while
    if found:
            print(userName, "is in file") # at posInFile-lenOfUser+1)
    else:
        pass

待检查:searchUserName('pirla','test.csv')
与其他答案一样,代码在第一次匹配时退出,但可以很容易地扩展到查找所有匹配项。
高温加热

42fyovps

42fyovps6#

#!/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

相关问题