The following code allows me to print a CSV output with the first "column" for the word and the second for the frequency. However, I have a second list called B that should be output in the same file.
A=[food:2,wine:1,dog:5]
B=[cat:3,bird:2]
cnt=Counter(A)
with open("list.csv", encoding='utf-8', mode='w') as fp:
fp.write('Word:Frequency\n')
for tag, count in cnt.items():
fp.write('{}:{}\n'.format(tag, count))
The final result should be
1. Word:Frequency:Word2:Frequency2
2. food:2:cat:3
3. wine:1:bird:2
4. dog:5
Could you help me? Thanks
Use itertools.zip_longest()
to pair up two sequences, and add filler when one is shorter than the other. You can fill with an empty tuple, so those columns will be omitted when you combine the two tuples.
Use the csv
module to convert these combined tuples to rows in the file.
from collections import Counter
import csv
from itertools import zip_longest
cnt1 = Counter(A)
cnt2 = Counter(B)
with open("list.csv", encoding='utf-8', mode='w') as fp:
csv_out = csv.writer(fp, delimiter=':')
csv_out.writerow(['Word', 'Freq', 'Word2', 'Freq2'])
for v1, v2 in zip_longest(cnt1.items(), cnt2.items(), fillvalue=tuple()):
csv_out.writerow(v1 + v2)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments