简体   繁体   中英

how to find specific string with a substring python

I have similar problem to this guy: find position of a substring in a string

The difference is that I don't know what my "mystr" is. I know my substring but my string in the input file could be random amount of words in any order, but i know one of those words include substring cola.

For example a csv file: fanta,coca_cola,sprite in any order.

If my substring is "cola", then how can I make a code that says

mystr.find('cola')

or

match = re.search(r"[^a-zA-Z](cola)[^a-zA-Z]", mystr)

or

if "cola" in mystr

When I don't know what my "mystr" is?

this is my code:

import csv

with open('first.csv', 'rb') as fp_in, open('second.csv', 'wb') as fp_out:
        reader = csv.DictReader(fp_in)
        rows = [row for row in reader]
        writer = csv.writer(fp_out, delimiter = ',')

        writer.writerow(["new_cola"])

        def headers1(name):
            if "cola" in name:
                    return row.get("cola")


        for row in rows:
                writer.writerow([headers1("cola")])

and the first.csv:

fanta,cocacola,banana
0,1,0
1,2,1                      

so it prints out

new_cola
""
""

when it should print out

new_cola
1
2

Here is a working example:

import csv

with open("first.csv", "rb") as fp_in, open("second.csv", "wb") as fp_out:
        reader = csv.DictReader(fp_in)
        writer = csv.writer(fp_out, delimiter = ",")

        writer.writerow(["new_cola"])

        def filter_cola(row):
            for k,v in row.iteritems():
                if "cola" in k:
                    yield v

        for row in reader:
            writer.writerow(list(filter_cola(row)))

Notes:

  • rows = [row for row in reader] is unnecessary and inefficient (here you convert a generator to list which consumes a lot of memory for huge data)
  • instead of return row.get("cola") you meant return row.get(name)
  • in the statement return row.get("cola") you access a variable outside of the current scope
  • you can also use the unix tool cut . For example:

     cut -d "," -f 2 < first.csv > second.csv 

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