简体   繁体   中英

Searching a CSV file using Regular Expressions

I'm trying to write a python script that will search through a .csv file using regular expressions to search for specific strings.

      for csv in glob.glob('C:\\Upload\\Uploads\\.csv'):
l = re.compile('[Longitude] + [Latitude]*', re.IGNORECASE)
f = re.match('[Longitude] + [Latitude]*', bFile, re.IGNORECASE)

    for csv in glob.glob('C:\\Upload\\Uploads\\.csv'):
m = re.compile('[!]+[@]+[#]+[$]+[%]+[^]+[&]+[*]+[(]+[)]+[{]+[}]',re.IGNORECASE)
n = re.search('[!]+[@]+[#]+[$]+[%]+[^]+[&]+^*]+[{]+[}]',bFile, re.IGNORECASE)

The bFile variable is the .csv file that I want to be searched through.

I am trying to search for Longitude and Latitude as field names, and then searching the .csv for any of the characters in the second expression. I am having trouble actually getting expressions to search through the .csv file accurately.

Any help would be greatly appreciated, thanks.

how about something a bit simpler?

# iterates over every csv file
for csv in glob.glob('C:\\Upload\\Uploads\\.csv'):
    # opens the file
    with open(csv, "r") as csv_reader:
        # iterates over every line in the file
        for line in csv_reader:
            # turns each line into a list of elements
            elements_in_line = line.strip("\r\n").split(",")
            # iterates over each element of each line of each file
            for element in elements_in_line:
                #you can do your code or what you want here.

though you question is hard to understand, specifically, what exactly you are searching for - since your regular expressions are not looking so great. this might be able to help you. you can decide at what level of iteration you want to search. and you dont even need to use regex, for instance.

if "longitude" in element:

would work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM