Reputation: 131
I have extracted a list of names (not perfect but ok) using NLTK. I want to save these to a csv file but keep getting the error:
TypeError: writerows() argument must be iterable
This is my code:
def get_human_names(text):
tokens = nltk.tokenize.word_tokenize(text)
pos = nltk.pos_tag(tokens)
sentt = nltk.ne_chunk(pos)
person_list = []
person = []
name = ""
for subtree in sentt.subtrees(filter=lambda t: t.label() == 'PERSON'):
for leaf in subtree.leaves():
person.append(leaf[0])
if len(person) > 1: #avoid grabbing lone surnames
for part in person:
name += part + ' '
if name[:-1] not in person_list:
person_list.append(name[:-1])
name = ''
person = []
return (person_list)
def first_and_last_names(text):
n = get_human_names(text)
for name in n:
last_first = HumanName(name).last + ', ' + HumanName(name).first
print(last_first)
names = first_and_last_names(text)
Grayling, Chris
Hannant, Ruth
General,
Services, Peter
Bogan, Gary
Parnership, Rail
import csv
with open('westtrannames.csv', 'w') as csvFile:
writer = csv.writer(csvFile)
writer.writerows(names)
csvFile.close()
I want a csv file with one row for the first name and the second row for the last name. Also, how would I append further results to the same file?
Upvotes: 0
Views: 505
Reputation: 82785
Couple of changes.
def first_and_last_names(text):
n = get_human_names(text)
result = []
for name in n:
last_first = HumanName(name).last + ', ' + HumanName(name).first
print(last_first)
result.append([last_first]) #Append last_name to a list
return result #Return list
names = first_and_last_names(text)
import csv
with open('westtrannames.csv', 'w') as csvFile:
writer = csv.writer(csvFile)
writer.writerows(names) #Names should be a list now.
Upvotes: 1