Как работать с типами данных в Python и подсчитывать количество слов в списке заголовков - PullRequest
0 голосов
/ 09 апреля 2019

У меня есть список заголовков статей, в которых я хочу подсчитать количество вхождений для каждого слова.(и удалите некоторые слова и символы) Входные данные находятся в файле .csv, где заголовки находятся в столбце «Заголовки»

У меня уже есть код, который выполняет работу (вставлено ниже), но, возможно, кто-то может помочья делаю это более элегантно.

import numpy as np
import pandas as pd
#imports Counter, as we will need it later:
from collections import Counter

df = pd.read_csv("Article_titles.csv")
print (df.head(10))

#Selecting the titles into variable
titles = []
titles = df.Title

remove_words_list = ["at","of","a","and","in","for","the","to","with","on","using","an","after","from","by","use","review","upper","new","system"]
remove_characters_list = ".:,-%()[]?'"

huge_title_list = []
#create a list of all article titles:
for i in range(len(titles)):
  clean_title = titles[i].lower().translate({ord(i): None for i in remove_characters_list})
  huge_title_list.append(clean_title)

total_words_string = " ".join(huge_title_list)
#join all article titles into one huge string

querywords = total_words_string.split()
#split the string into a series of words

resultwords = [word for word in querywords if word not in remove_words_list]
#From stackoverflow

resultwords_as_list = list( Counter(resultwords).items())

#Convert resultwords_list to dataframe, then convert count to numbers and finally sorting.
resultframe = pd.DataFrame(np.array(resultwords_as_list).reshape(-1,2), columns = ("Keyword","Count"))
resultframe.Count = pd.to_numeric(resultframe.Count)
sortedframe = resultframe.sort_values(by='Count',ascending=False).reset_index(drop=True)
print(sortedframe[0:50])

пример ввода:

Titles | other_field | other_field2

"Current status of prognostic factors in patients with metastatic renal cell carcinoma." |"asdf"|12
"Sentinel lymph node biopsy in clinically node-negative Merkel cell carcinoma: the Westmead Hospital experience." |"asdf"|15

желаемый вывод:

Word | Count

carcinoma | 2

cell | 2

biopsy | 1

clinically | 1

....

...

1 Ответ

0 голосов
/ 09 апреля 2019

Попробуйте следующий метод, чтобы получить количество.После этого удалите ненужные слова.

import pandas as pd
import numpy as np
import re

a="Current status of prognostic factors in patients with metastatic renal cell carcinoma."
b="Sentinel lymph node biopsy in clinically node-negative Merkel cell carcinoma: the Westmead Hospital experience."

d=[]
data=pd.DataFrame([a,b],columns=["Titles"])
for i in data["Titles"]:
    d.extend(re.split(" |\.|:|,|-|%|\(|\)|\[|\]|\?|'",i))

print(np.unique(d,return_counts=True))
...