Reputation: 798
My python script counts how many times a word list appears in a text. Script works but when I try to write results in a CSV file separated by semicolons but it doesn't work.
My code:
import csv
wordslist = ["Bob", "car"]
text = "Bob loves his Mustang car, but Bob wants a Ferrari car because Ferrari is a fastest car."
for word in wordslist :
resultCar = str(word) + "; " + str(text.count(word))
print resultCar
carCountsCsv = open("carcounts.csv", "wb")
with carCountsCsv:
writer = csv.writer(carCountsCsv)
writer.writerow(resultCar)
And my CSV file results is:
c,a,r,;, ,3
I don't understand why my result appear in the same row, I want to have this result like in the console:
Bob;2
car;3
Any help would be appreciated
Upvotes: 3
Views: 5838
Reputation: 26139
Since your output is CSV already, consider raw pipe. Say our file is named bob_car.py
.
wordslist = ["Bob", "car"]
text = "Bob loves his Mustang car, but Bob wants a Ferrari car because Ferrari is a fastest car."
for word in wordslist:
print "%s; %i" % (word, text.count(word))
Then simply do:
python bob_car.py > carcounts.csv
Upvotes: 2
Reputation: 4855
First, open the file once before the loop, otherwise you will overwrite the previous line and will end up with a file that only contains the last row.
with open("carcounts.csv", "w") as carCountsCsv:
Then, since you want ;
as the separator in your CSV file, you don't need to use csv_writer
. You've already created a string with the right separator. Just write the lines to a normal file.
with open("carcounts.csv", "w") as carCountsCsv:
for word in wordslist :
resultCar = str(word) + "; " + str(text.count(word)) + "\n"
print(resultCar)
carCountsCsv.write(resultCar)
If you do want to use the CSV library, you will want to pass it the delimiter that you want when you create the writer. Then you pass it a list with the elements of each row and it will add the delimiter for you.
with open("carcounts.csv", "w", newline='') as carCountsCsv:
writer = csv.writer(carCountsCsv, delimiter=';')
for word in wordslist:
resultCar = [str(word), str(text.count(word))]
print(resultCar)
writer.writerow(resultCar)
Note that when you open the file, specify newline=''
. The csv.writer
will add the newline for you. If you forget this, you will get double newlines in your CSV file.
Upvotes: 2