-1

I have a list of different words divided with ':' in a .txt, as such:

banana:pinapple
apple:grapes
orange:nuts
...

How can I get the number of lines that have a word on the left of the semicolon and print that number?

I am using this to seperate them:

string1, string2 = line.split(':')

I want to print the number sort of like this:

print(number of lines where there exists is a string1)
Jesper
  • 5
  • 4
  • Naive way - after splitting combine them as a single list and use Counter – Aditya May 14 '17 at 15:27
  • @aryamccarthy I wanted to print the amount so I've tried print(len(string1)) but I don't really know what to search for. – Jesper May 14 '17 at 15:28
  • Other way which is a bit easy will be use a dict with default key implemented – Aditya May 14 '17 at 15:28
  • @ADITYA it's not clear whether the intent is to count each string or simply get the number of lines which are not empty to the left of the colon. – Arya McCarthy May 14 '17 at 15:29
  • @ aryamccarthy Simply count written in brackets – Aditya May 14 '17 at 15:30
  • @aryamccarthy I just want to get the number of lines which are not empty to the left – Jesper May 14 '17 at 15:30
  • The example you have given us doesn't make sense given your question about counting the amount of words on the left. If it's a list containing only strings where two words have `:` between them, you can just get the length of your list to get the number of the words on the left since it's the same as the number on the right and the same as the number of strings in your list. Please provide more information and/or edit your question/example. – rbaleksandar May 14 '17 at 15:30
  • Already submitted an edit request – Aditya May 14 '17 at 15:31
  • Edited to try to be more clear – Jesper May 14 '17 at 15:37
  • @Jesper Has your question been sufficiently addressed? If not, what's unclear? If so, you should mark the checkbox beside the correct answer. – Arya McCarthy May 15 '17 at 00:22

4 Answers4

0
count = 0
for line in f:
    string1, string2 = line.split(':')
    if string1:
        count += 1
print(count)

Your question asks about the number of words on the left, which is exactly what this counts. This handles the case where the line is :foo. Still, you haven't suggested that there are ever lines without a colon or lines with more than one. Additionally, you haven't said there will be more than one word on the left. I choose to ignore these cases since you haven't indicated their existence.

Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56
0
fileName = 'myfile.txt'

counterDict = {}

with open(fileName,'r') as fh:
  for line in fh:
    left,right = line.rstrip('\n').split(':')
    counterDict[left] = counterDict.get(left,0)+1  

print(counterDict)

# cat myfile.txt

banana:pinapple
apple:grapes
orange:nuts
banana:pinapple
apple:grapes
orange:nuts
banana:pinapple
apple:grapes
orange:nuts

# Result

{'banana':3,'apple':3,'orange':3}
Fuji Komalan
  • 1,979
  • 16
  • 25
0

So I'm not sure I understand your question based on all the answers provided. All you want to know is how to count the number of lines in a text file?

Yes I see you said "That have a word on the left of the colon", but why would you have a colon on a line with out any other text? Your saying that your program writes the text in such a way that it's "example":"example" right?

If that's the case you wouldn't have a colon on a line with out any other text, unless you intentionally input nothing which is still something.

def get_total_lines(self, path):
    counter = 0
    try:
        if os.path.isfile(path):
            with open(path, 'r') as inFile:
                for i in enumerate(inFile):
                    counter = counter + 1
                    return str(counter)
        elif not os.path.isfile(path):
            print("Error: The file you're attempting to read does not exist, aborting reading process...")
    except IOError as exception:
        raise IOError('%s: %s' % (path, exception.strerror))
        return None

That's got some basic form of error checking, here is one with out it.

def get_total_lines(self, path):
    counter = 0
    with open(path, 'r') as inFile:
        for i in enumerate(inFile):
            counter = counter + 1
            return str(counter) # could be int or w/e else you want it to be

That will count the lines, if you want to strip off a word or the colon it can be easily adapted to do that.

suroh
  • 917
  • 1
  • 10
  • 26
-1

Just got the number of lines instead like this:

with open(listname) as list:
    lines = len(list.readlines())
Jesper
  • 5
  • 4