Reputation: 5931
For a given string, I'm trying to count the number of appearances of each word and emoji. I did it already here for emojis that consists only from 1 emoji. The problem is that a lot of the current emojis are composed from a few emojis.
Like the emoji π¨βπ©βπ¦βπ¦ consists of four emojis - π¨β π©β π¦β π¦, and emojis with human skin color, for example π π½ is π π½ etc.
The problem boils down to how to split the string in the right order, and then counting them is easy.
There are some good questions that addressed the same thing, like link1 and link2 , but none of them applies to the general solution (or the solution is outdated or I just can't figure it out).
For example, if the string would be hello π©πΎβπ emoji hello π¨βπ©βπ¦βπ¦
, then I'll have {'hello':2, 'emoji':1, 'π¨βπ©βπ¦βπ¦':1, 'π©πΎβπ':1}
My strings are from Whatsapp, and all were encoded in utf8.
I had many bad attempts. Help would be appreciated.
Upvotes: 3
Views: 2558
Reputation: 1
emoji.UNICODE_EMOJI is a dictionary with structure
{'en':
{'π₯': ':1st_place_medal:',
'π₯': ':2nd_place_medal:',
'π₯': ':3rd_place_medal:'
... }
}
so you will need to use emoji.UNICODE_EMOJI['en']
for the above code to work.
Upvotes: 0
Reputation: 5931
Huge thanks Mark Tolonen. Now in order to count words and emojis and words in a given string, I'll use emoji.UNICOME_EMOJI
in order to decide what is an emoji and what is not (from the emoji
package), and then remove from the string the emojis.
Currently not an ideal answer, but it works and I'll edit if it will be changed.
import emoji
import regex
def split_count(text):
total_emoji = []
data = regex.findall(r'\X',text)
flag = False
for word in data:
if any(char in emoji.UNICODE_EMOJI for char in word):
total_emoji += [word] # total_emoji is a list of all emojis
# Remove from the given text the emojis
for current in total_emoji:
text = text.replace(current, '')
return Counter(text.split() + total_emoji)
text_string = "πΉπΉπΉπΉπΉhere hello world helloπ¨βπ©βπ¦βπ¦π
π½"
final_counter = split_count(text_string)
Output:
final_counter
Counter({'hello': 2,
'here': 1,
'world': 1,
'π¨\u200dπ©\u200dπ¦\u200dπ¦': 1,
'πΉ': 5,
'π
π½': 1})
Upvotes: 3
Reputation: 177406
Use the 3rd party regex module, which supports recognizing grapheme clusters (sequences of Unicode codepoints rendered as a single character):
>>> import regex
>>> s='π¨βπ©βπ¦βπ¦π
π½'
>>> regex.findall(r'\X',s)
['π¨\u200dπ©\u200dπ¦\u200dπ¦', 'π
π½']
>>> for c in regex.findall('\X',s):
... print(c)
...
π¨βπ©βπ¦βπ¦
π
π½
To count them:
>>> data = regex.findall(r'\X',s)
>>> from collections import Counter
>>> Counter(data)
Counter({'π¨\u200dπ©\u200dπ¦\u200dπ¦': 1, 'π
π½': 1})
Upvotes: 2