В WordCloud на Python я бы хотел объединить два языка - PullRequest
1 голос
/ 12 марта 2020

В WordCloud на Python Я хотел бы объединить два языка в одну картинку (английский sh, арабский c), но я не смог добавить язык арабский c, поскольку вместо этого вы видите квадраты слов и когда я вызываю библиотеку Arabic_reshaper и заставляю ее читать файл CSV, он показывает мне язык арабский c и заставляет язык Engli sh в виде квадратов

    wordcloud = WordCloud(
                          collocations = False,
                          width=1600, height=800,
                          background_color='white',
                          stopwords=stopwords,
                          max_words=150,
                          random_state=42,
                          #font_path='/Users/mac/b.TTF'
                         ).generate(' '.join(df['body_new']))
print(wordcloud)
plt.figure(figsize=(9,8))
fig = plt.figure(1)
plt.imshow(wordcloud)
plt.axis('off')
plt.show()

увидеть ее положить два языка, но вместо квадратов вместо слов арабский c enter image description here

не так, как это максимум два языка

enter image description here

1 Ответ

0 голосов
/ 21 апреля 2020

Я уже давно борюсь с той же проблемой, и лучший способ справиться с ней - это функция generate_from_frequencies(). Вам также нужен правильный шрифт для Arabi c. «Shorooq» будет работать нормально и доступен онлайн бесплатно. Вот быстрое исправление вашего кода:

from arabic_reshaper import arabic_reshaper
from bidi.algorithm import get_display
from nltk.corpus import stopwords
from itertools import islice


text = " ".join(line for lines in df['body_new'])
stop_ar = stopwords.words('arabic') 
# add more stop words here like numbers, special characters, etc. It should be customized for your project

top_words = {}
words = text.split()
for w in words:
    if w in stop_ar:
        continue
    else:
        if w not in top_words:
            top_words[w] = 1
        else:
            top_words[w] +=1

# Sort the dictionary of the most frequent words
top_words = {k: v for k, v in sorted(top_words.items(), key=lambda item: item[1], reverse = True)}

# select the first 150 most frequent words
def take(n, iterable):
    "Return first n items of the iterable as a list"
    return list(islice(iterable, n))
for_wc = take(150, top_words.items())

# you need to reshape your words to be shown properly and turn the result into a dictionary
dic_data = {}
for t in for_wc:
    r = arabic_reshaper.reshape(t[0]) # connect Arabic letters
    bdt = get_display(r) # right to left
    dic_data[bdt] = t[1] 

# Plot
wc = WordCloud(background_color="white", width=1600, height=800,max_words=400, font_path='fonts/Shoroq.ttf').generate_from_frequencies(dic_data)
plt.figure(figsize=(16,8))
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show()

Важно:

get_display() или reshape() может привести к ошибке. Это потому, что в вашем тексте есть странный символ, с которым эти функции не могут справиться. Однако найти его не должно быть так сложно, так как вы используете только 150 слов для отображения на вашем графике. Найдите его и добавьте к своим стоп-словам и повторите код.

...