Search code examples
pythoncsvcell

Writing to a specific cell in csv using python


I have a set of sentences in a text file and I have the verbs from it marked as column headers in csv file. I need to mark a '1' in the specific cell under the right column, if the verb is present in that sentence. e.g.

If my sentence is: I like this movie.

My csv file has the headers: like, hate and loathe.

Then I need my csv file to look like

  like       hate       loathe
   1

Thanks in advance.

Here's the code I have tried:

with open('verb.csv', 'wb') as csvn:
    cwriter = csv.writer(csvn)
    cwriter.writerow([d for d in verbs])

where verbs is my list of verbs. This prints the verbs as column headers in csv file.

for l, label in file:
    t = nltk.word_tokenize(l)
    tt = nltk.pos_tag(t)
    for pos in tt:
        for p in pos[1]:
            c = 0
            if(p == 'V'):
                w = pos[0]
                for l in verbs:
                    if w == l:
                        print(c)
                        continue
                    else:
                        c+=1

Now w contains the verb and I can search for a matching word in the list of verbs and obtain its location, but I don't have a clue how I could mark the corresponding location in the csv file as 1. My python version is 2.7.


Solution

  • I'd create an empty list after where you create your counter. the list has the same length as your n verbs.

    c = 0
    emptylist = [""] * len(verbs)
    

    Then when you run through your verb list, use the counter (c) (btw, are you sure it's not print(l) you want to write in your code?) as the position in the empty list. I'd change the following part:

    if w == l:
        print(c)
        emptylist[c] = 1
        ## then write emptylist to the csv with csv.writerow(emtptylist)
        continue