Python Forum
To count a number of strings in a txt file with python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: To count a number of strings in a txt file with python (/thread-2977.html)



To count a number of strings in a txt file with python - jpeich - Apr-22-2017

I have a .txt file that contain ten words(for example ten names) and i wanted to know how can i count the number of names, in this case 10. If i use len(names), the console gives me the length of the word, not the number of the names. Thank you


RE: To count a number of strings in a txt file with python - Bass - Apr-22-2017

Hi,

Here is a link that shows a number of examples to tackle what looks like the same problem. The thread is calledSign up

How to get line count cheaply in Python?


http://stackoverflow.com/questions/845058/how-to-get-line-count-cheaply-in-python

You may want to watch out that these refer to the same flavour of Python (i.e. Pre/Post version Three)

Good Luck

Bass


RE: To count a number of strings in a txt file with python - snippsat - Apr-22-2017

Post what you have tried with code jpeich,read this.

@Bass
We try to answer relative simple question like this yourself in the forum.
It can be okay to reefer an answer in other forum in more difficult cases.
The scale is different to "hundreds of thousands of lines" in that thread.

We can all just search Stack Overflow and post link to answer there,
but that's not much effort and not what we want this forum to be about.


RE: To count a number of strings in a txt file with python - wavic - Apr-22-2017

You don't need python to count words. 

$ echo "We try to answer relative simple question like this yourself in the forum" | wc -w

13



RE: To count a number of strings in a txt file with python - Bass - Apr-23-2017

(Apr-22-2017, 09:07 PM)snippsat Wrote: @snippsat

Quote:@Bass
We try to answer relative simple question like this yourself in the forum.
It can be okay to reefer an answer in other forum in more difficult cases.
The scale is different to "hundreds of thousands of lines" in that thread.

We can all just search Stack Overflow and post link to answer there,
but that's not much effort and not what we want this forum to be about.

Understood. Thank you for the advice and explanation.
Bass



RE: To count a number of strings in a txt file with python - nilamo - Apr-29-2017

>>> text = """
... spam eggs
... fish
... carrot dog worm
... mouse keyboard history lesson""".split()
>>>
>>> # with open(filename) as text:
...
>>> word_count = 0
>>> for line in text:
...   word_count += len(line.split())
...
>>> word_count
10