user3393616
user3393616

Reputation: 19

Getting count of certain word in txt file in Python?

i'm trying to get number of word in certain txt file.

I've tried this but it's not working due to "AttributeError: 'list' object has no attribute 'split'":

 words = 0
 for wordcount in textfile.readlines().split(":"):
     if wordcount == event.getPlayer().getName():
        words += 1

Is there any easier or less complicated way to do this?

Here's my text file:

b2:PlayerName:Location{world=CraftWorld{name=world},x=224.23016231506807,y=71.0,z=190.2291303186236,pitch=31.349741,yaw=-333.30002}

What I want is to search for "PlayerName" which is players name and if player has 5 entries (actually, if word "PlayerName" has been five times written to file) it will add +5 to words.

P.S. I'm not sure if this is good for security, because it's an multiplayer game, so it could be many nicknames starting with "PlayerName" such as "PlayerName1337" or whatever, will this cause problem?

Upvotes: 1

Views: 2329

Answers (3)

vaultah
vaultah

Reputation: 46593

Should work

 words = 0
 for wordcount in textfile.read().split(":"):
     if wordcount == event.getPlayer().getName():
        words += 1

Here's the difference: .readlines() produces a list and .read() produces a string that you can split into list.

Better approach that won't count wrong things:

 words = 0
 for line in textfile.readlines():
      # I assume that player name position is fixed
     word = line.split(':')[1]
     if word == event.getPlayer().getName():
        words += 1

And yes, there is a security concern if there are players with the same names or with : in their names.

  1. The problem with equal names is that your code doesn't know to what player a line belongs.

  2. If there will be a colon in player's name you code will also split it.

I urge you to assign some sort of unique immutable identifier for every player and use a database instead of text files that will handle all this stuff for you.

Upvotes: 1

khagler
khagler

Reputation: 4056

You can find how many times a word occurs in a string with count:

words = textfile.read().count('PlayerName')

Upvotes: 0

Retozi
Retozi

Reputation: 7891

there is an even easier way if you want to count multiple names at once... use the Counter from the collections module

from collections import Counter

counter = Counter([line.split(':') for line in textfile.readlines()])

Counter will behave like a dict, so you will count all the names at once and if you need to, you can efficiently look up the count for more than one name.

At the moment your script counts only one name at a time per loop

you can access the count like so

counter[event.getPlayer().getName()]

I bet you will eventually want to count more than one name. If you do, you should avoid reading the textfile more than once.

Upvotes: 1

Related Questions