I have a plain research paper text file and I am asked to count the number of quotes in that file using Python. How would I go about doing this? Is there a way to count the number of occurrences of the character " in the file?
2 Answers
This short program will do:
import sys
print(sum(line.count(sys.argv[1]) for line in sys.stdin))One-liner and usage:
python3 -c 'import sys; print(sum(line.count(sys.argv[1]) for line in sys.stdin))' '"' < data.txtAn arguably simpler, non-Python solution based on tr and wc would be:
tr -c -d '"' < data.txt | wc -cIf there's at most one match per line you can also use grep in “count” mode:
grep -cFe '"' data.txt You can use count() it returns the number of (non-overlapping) occurrences