Ejemplo n.º 1
0
 def predict(message):
     name = []
     address = []
     phone_number = ""
     code = ""
     tokens = ner(message)
     print("tokens: {}".format(tokens))
     for token in tokens:
         if 'LOC' in token[3] and 'kh' not in token[0].lower():   #location
             address.append(token[0])
         if 'PER' in token[3] and 'kh' not in token[0].lower():   #person
             name.append(token[0])
     if name != []:
         name = ' '.join(name)
     else:
         name = ''
     if address != []:
         address = ' '.join(address)
     else:
         address = ''
     #regex phonenumber
     pattern_phone_number = '0\d{9}|\+84\d{9}'    
     phone_numbers = re.findall(pattern_phone_number, message)
     #regex code customer
     pattern_code = '[Pp].{5}\d{7}'
     codes = re.findall(pattern_code, message)
     if len(phone_numbers) > 0:
         phone_number = phone_numbers[-1]
     if len(codes)> 0:
         code = codes[-1]
     print("ner: ", name, address, phone_number, code)
     return name, address, phone_number, code
     
Ejemplo n.º 2
0
def isAnyLOC(message_text):
    isLOC = False
    res = ner(message_text)
    for i in range (len(res)):
        if res[i][3] == "I-LOC" or res[i][3] == "B-LOC":
            isLOC = True
    return isLOC
Ejemplo n.º 3
0
def find_loc(text):
    loc = []
    for x in ner(text):
        if "LOC" in x[3]:
            loc.append(x[0])
    loc_str = ','.join(loc)
    return loc_str
Ejemplo n.º 4
0
 def process(self, message, **kwargs):
     """Retrieve the text message, pass it to the classifier
         and append the prediction results to the message class."""
     if 'text' in message.data:
         tokens = underthesea.ner(message.data['text'])
         entities = self.convert_to_rasa(tokens)
         message.set("entities", entities, add_to_output=True)
Ejemplo n.º 5
0
def find_per(text):
    per = []
    for x in ner(text):
        if "PER" in x[3]:
            per.append(x[0])
    per_str = ','.join(per)
    return per_str
Ejemplo n.º 6
0
    def next_State(self, text, product):
        if (check_endProcess(text)):
            return end_state()
        tokens = vnltk.ner(text)
        N = [token[0] for token in tokens if token[1] in ['N', 'M']]
        new_category = object_parse(N)
        product['price'] = price_parse(text)
        product['branch'] = branch_parse(tokens)
        if (new_category != [] and new_category != product['category']):
            product['category'] = new_category
            if product['price'] != '' and product['branch'] != '':
                return completeInfo_state()
            if product['price'] != '' and product['branch'] == '':
                return knowCP_state()
            if product['price'] == '' and product['branch'] != '':
                return knowCB_state()
            return knowCategory_state()

        if 'Điện thoại' not in product['category'] and 'Laptop' not in product[
                'category']:
            return completeInfo_state()

        if product['price'] != '' and product['branch'] == '':
            return knowCP_state()

        if product['price'] == '' and product['branch'] != '':
            return knowCB_state()

        if product['price'] != '' and product['branch'] != '':
            return completeInfo_state()
Ejemplo n.º 7
0
def get_temp(st, session, data):

    url_img_weather = "http://openweathermap.org/img/w/"

    result = ner(st.title())

    for i in result:
        if i[3] == 'B-LOC':
            city = i[0]
            break

    if 'city' not in locals():
        return ("Cho em tỉnh thành phố đi", 1)

    json_data = get_json_weather(city)

    if json_data['cod'] == 200:
        res = u"<strong>Thời tiết ở " + city + ".</strong><br/>"
        res += u"Tình trạng: " + json_data['weather'][0][
            'description'] + ".<img src='" + url_img_weather + json_data[
                'weather'][0]['icon'] + ".png'/><br/>"
        res += u"Nhiệt độ trung bình: " + str(
            json_data['main']['temp']) + " độ C.<br/>"
        res += u"Nhiệt độ cao nhất: " + str(
            json_data['main']['temp_max']) + " độ C.<br/>"
        res += u"Nhiệt độ thấp nhất: " + str(
            json_data['main']['temp_min']) + " độ C.<br/>"
        res += u"Độ ẩm: " + str(json_data['main']['humidity']) + "%.<br/>"
        return (res, 1)
    else:
        return "<strong>Lỗi: " + json_data["message"] + "</strong>"
Ejemplo n.º 8
0
def getLOC(message_text):
    filename = "data/dataset_XY_XLS_updatedbytho_ver2_2.xlsx"
    df = pd.read_excel(filename, sheet_name="listofWorkingplace", encoding="utf8")

    # use underthesea tool: ner to N-E-R sentence
    res = ner(message_text)
    
    # filter the result to get the I-LOC or B-LOC
    loc_VN = list(df.loc[:,"Name"])
    loc_stop = ['huyện', 'tỉnh', 'thị xã', 'quận', 'khu phố', 'phường', 'ấp', 'thành phố', 'thành phố mới']
    locIDX = []
    for i in range (len(res)):
        if res[i][3] == "I-LOC" or res[i][3] == "B-LOC":
            if res[i][0] not in loc_stop and res[i][0] in loc_VN:
                locIDX.append(i)
    # dict-orize to transform to value of Rasa
    dictLOC = {}
    count = []
    countLOC = []
    for i in range(len(locIDX)):
        count.append("LOC "+ str(i))
    for i in locIDX:
        countLOC.append(res[i][0])
    dictLOC = dict(zip(count, countLOC))

    return dictLOC
Ejemplo n.º 9
0
def get_temp(st, track, data):

    url_img_weather = "http://openweathermap.org/img/w/"

    result = ner(st.title())

    for i in result:
        if i[3] == 'B-LOC':
            city = i[0]
            break

    if 'city' not in locals():
        return ({"text": "Cho em tỉnh thành phố đi"}, 1)

    json_data = get_json_weather(city)

    if json_data['cod'] == 200:
        res = u"Thời tiết ở " + city + "\n"
        res += u"Tình trạng: " + json_data['weather'][0]['description'] + "\n"
        res += u"Nhiệt độ trung bình: " + str(
            json_data['main']['temp']) + " độ C\n"
        res += u"Nhiệt độ cao nhất: " + str(
            json_data['main']['temp_max']) + " độ C\n"
        res += u"Nhiệt độ thấp nhất: " + str(
            json_data['main']['temp_min']) + " độ C\n"
        res += u"Độ ẩm: " + str(json_data['main']['humidity']) + "%"
        return ({"text": res}, 1)
    else:
        return {"text": "Lỗi: " + json_data["message"]}
Ejemplo n.º 10
0
 def check_relevant(self, text):
     tokens = vnltk.ner(text)
     N = [token[0] for token in tokens if token[1] in ['N', 'M']]
     new_category = object_parse(N)
     price = price_parse(text)
     branch = branch_parse(tokens)
     return price != '' or new_category != [] or branch != '' or check_endProcess(
         text)
Ejemplo n.º 11
0
def ner(request):
    result = {}
    try:
        text = json.loads(request.body.decode("utf-8"))["text"]
        tags = uts.ner(text)
        result["output"] = tags
    except:
        result = {"error": "Bad request!"}
    return JsonResponse(result)
Ejemplo n.º 12
0
def selectPlaceByNer(list):
    """
     một phần tử trong list sẽ gồm 4 trường.
     VD: ('Việt Nam', 'Np', 'B-NP', 'B-LOC')
    """
    list = ner(list)
    for text in list:
        if text[3] == "B-LOC" or text[3] == "I-LOC":
            yield (text[0])
Ejemplo n.º 13
0
def get_numbers_in_desc(df):
	numbers_list = []
	for i in range (len(df)):
	    text = df['description_2'][i]
	    tags = ner(text)
	    numbers_result = extract_info(tags)
	    numbers_list.append({i : numbers_result})

	return numbers_list
def get_ner(text):
    res = ner(text)
    words = [r[0] for r in res]
    tags = [t[3] for t in res]

    chunks = get_entities(tags)
    res = []
    for chunk_type, chunk_start, chunk_end in chunks:
        res.append(' '.join(words[chunk_start:chunk_end]))
    return res
Ejemplo n.º 15
0
def getNerName(message_text):
    filename = "data/dataset_XY_XLS_updatedbytho_ver2_2.xlsx"
    df = pd.read_excel(filename, sheet_name="listofWorkingplace", encoding="utf8")

    # use underthesea tool: ner to N-E-R sentence
    res = ner(message_text)
    
    # filter the result to get the I-LOC or B-LOC
    loc_VN = list(df.loc[:,"Name"])
    loc_stop = ['huyện', 'tỉnh', 'thị xã', 'quận', 'khu phố', 'phường', 'ấp', 'thành phố', 'thành phố mới']
    locIDX = []
    locNAME=[]
    res = ner(message_text)
    print('res: ', res)
    for i in range (len(res)):
        if res[i][0] not in loc_stop and res[i][0] in loc_VN:
            if res[i][3] == "I-LOC" or res[i][3] == "B-LOC":
                locIDX.append(i)
    for i in locIDX:
        locNAME.append(res[i][0])
    return locIDX, locNAME
Ejemplo n.º 16
0
def color_keywords(s, keywords):
    def color(kw):
        nonlocal s
        case_insensitive = re.compile(r'\b%s\b' % kw, re.IGNORECASE)
        s = case_insensitive.sub(answer_color + kw + Back.RESET + Fore.RESET,
                                 s)

    for kw in keywords:
        color(kw)
        for word in ner(kw):
            if word[1] == 'Np':
                color(word[0])
    return s
Ejemplo n.º 17
0
def getName(content):
    text = ner(content)
    names = []
    trigger = True
    for word in text:
        if (word[-1].find('PER') != -1):
            names.append(word[0])
            if (word[-1] == 'B-PER'):
                trigger = False
        elif not trigger:
            break
    nameEnt = ' '.join(names)
    return nameEnt
Ejemplo n.º 18
0
    def next_State(self, text, product):
        tokens = vnltk.ner(text)
        N = [token[0] for token in tokens if token[1] == 'N']
        product['category'] = object_parse(N)
        product['price'] = price_parse(text)
        product['branch'] = branch_parse(tokens)

        if product['price'] != '' and product['branch'] != '':
            return completeInfo_state()
        if product['price'] != '' and product['branch'] == '':
            return knowCP_state()
        if product['price'] == '' and product['branch'] != '':
            return knowCB_state()

        return knowCategory_state()
Ejemplo n.º 19
0
    def next_State(self, text, product):
        if (check_endProcess(text)):
            return end_state()
        tokens = vnltk.ner(text)
        querry = self.question_parse(text)
        if (querry != []):
            return ask_state(querry, self.current_product)

        if (self.isNextItem(tokens)):
            return suggest_state()

        if (self.isBought(tokens)):
            return bought_state()

        return end_state()
Ejemplo n.º 20
0
def find_per_loc(text):

    # text = """ "Nỗi ám ảnh khách hàng""Trong kinh doanh, các lãnh đạo của Amazon luôn lấy khách hàng làm gốc, không ngừng tìm kiếm và nõ lực gìn giữ lòng tin của khách hàng. Dù có quan tâm đến đối thủ nhưng họ thường bị ám ảnh bởi khách hàng nhiều hơn"", John Rossman- cựu giám đốc dịch vụ doanh nghiệp của Amazon.com nhận xét trong cuốn sách viết về phương thức kinh doanh của gã khổng lồ thương mại điện tử này.  Theo Rossman, sự ám ảnh về khách hàng của Jeff Bezos là một thứ gì đó vượt xa nỗi ám ảnh đơn thuần- nó là hội chứng tâm lý khiến Jeff có thể buông những lời chỉ trích cay độc hay đưa ra nhiều nhận định khắt khe đối với cộng sự tại Amazon khi họ không đáp ứng được các tiêu chuẩn của Jeff về dịch vụ khách hàng. Điều này bắt nguồn từ khả năng đặc biệt của Jeff trong việc đặt bản thân vào vị trí của khách hàng, từ đó suy ra những nhu cầu và mong muốn của họ, để sau đó phát triển một hệ thống có thể đáp ứng các nhu cầu và mong muốn đó tốt hơn bất kỳ ai.  ""Cách tiếp cận kinh doanh này chính là điểm cốt lõi trong tài năng thiên bẩm của Jeff"", Rossman nhận định. Cụ thể là rất lâu trước khi truyền thông xã hội tạo ra cuộc cách mạng rộng rãi trong thế giới bán lẻ, khi những mạng lưới thông tin minh bạch được hình thành, kết nối các công ty với khách hàng hiện tại, khách hàng tiềm năng và cả những kẻ gièm pha; rất lâu trước khi những công ty như Zappos.com bắt đầu lấy dịch vụ khách hàng làm nền tảng cho mô hình kinh doanh; cũng như rất lâu trước khi Jeff nhận ra tầm nhìn toàn diện của bản thân đối với Amazon.com, ông đã quán triệt sâu sắc trong nội bộ công ty về 2 chân lý trong lĩnh vực dịch vụ khách:  Một là Khi một công ty khiến cho một khách hàng không hài lòng, người đó sẽ không chỉ nói điều đó với một, hai hay ba người khác, mà sẽ nói với rất, rất nhiều người.  Hai là Dịch vụ khách hàng tốt nhất là không có dịch vụ nào hết- bởi trải nghiệm tốt nhất có được khi khách hàng không bao giờ phải yêu cầu một sự hỗ trợ nào cả.  Hạn chế tối đa sự tham gia của con người  Tất nhiên, việc xây dựng một mô hình kinh doanh thực tế không yêu cầu bất kỳ dịch vụ khách hàng nào cũng viễn tưởng như việc chế tạo động cơ vĩnh cửu. Nhưng ngay từ giai đoạn đầu của cuộc cách mạng Internet, Jeff đã nhận thấy mô hình bán lẻ trực tuyến có thể mở đường cho nhiều điều khả thi. Từ lâu, ông cũng đã nhận ra mối đe dọa lớn nhất đối với trải nghiệm khách hàng là khi con người tham gia vào và làm cho mọi thứ rối tung lên. Do đó, ông đưa đến kết luận, chìa khóa để tạo ra trải nghiệm dễ chịu và suôn sẽ nhất cho khách hàng là hạn chế tối đa sự tham gia của con người thông qua quá trình đổi mới và công nghệ.  Tất nhiên Amazon vẫn cần con người. Và Jeff Bezos là người có kỹ năng trong việc tuyển dụng, đánh giá và giữ chân những nhân tài hàng đầu thế giới. Nhưng mục tiêu của Amazon luôn là giảm thiểu thời gian và công sức mà con người phải tiêu tốn vào những tương tác dịch vụ thông thường, giải phóng sức lao động để họ có thể sáng tạo những cách thức mới làm hài lòng khách hàng.  Quan điểm kinh doanh của Jeff đã dẫn tới một số chiến thuật khá khác thường. Trở lại thời điểm những năm 1990, Amazon.com cố tình làm cho việc tìm kiếm só điện thoại dịch vụ chăm sóc khách hàng trở nên khó khăn. Điều này khiến nhiều người nghi ngại và cho rằng động thái đó phản ánh sự không tôn trọng khách hàng. Nhưng rồi họ nhanh chóng nhận ra rằng, những kỹ sư của Jeff đã tạo ra một công nghệ đột phá giúp họ giải quyết những yêu cầu dịch vụ gần như ngay lập tức mà không cần đến sự can thiệp của con người. Sau tất cả, 98% các câu hỏi của người mua dành cho một nhà bán lẻ như Amazon đều quy về ""Đồ của tôi đang ở đâu?"" Do đó, một công cụ theo dõi trực tuyến ra đời, giúp khách hàng theo dõi việc vận chuyển hàng từ kho tới tận cửa nhà, bỏ qua yêu cầu phải có một trung tâm liên lạc lớn, cồng kềnh và tốn kém.  Jeff tin rằng mọi người không thích nói chuyện với các nhân viên chăm sóc khách hàng, và ông đã đúng. Ông chỉ cung cấp dữ liệu, công cụ và hướng dẫn để người mua có thể trả lời những câu hỏi của chính họ.  Giờ đây khách hàng đều chờ đợi và yêu cầu ""công nghệ chăm sóc khách hàng tự phục vụ"" do Bill Price và David Jaffe dưa ra trong cuốn sách The best service is no service vào năm 2008: Trải nghiệm của khách hàng càng trơn tru, khách hàng càng trugn thành và chi phí vận hành càng thấp (bao gồm cả chi phí marketing và quảng cáo).  Hai tác giả này lý giải: ""Amazon đã giảm được 90% lượng liên lạc mỗi đơn hàng (CPO- Contacts per order), nghĩa là họ có thể tăng số lượng đơn hàng (và doanh thu) lên gấp 9 lần trong khi vẫn duy trì mức chi phí chăm sóc khách hàng như cũ (bao gồm chi phí nhân viên và các chi phí vận hành liên quan). Đây là nhân tố chủ chốt góp phần vào khả năng sinh lời của công ty bắt đầu từ năm 2002"".  (*) Nội dung tham khảo cuốn sách Phương thức Amazon- Tác giả John Rossman, Vũ Khánh Thịnh dịch.Quyền lực đáng sợ của Amazon: Các công ty 'lèo tèo' làm ngơ cũng không được, cạnh tranh cũng chẳng xong, đành phải hợp tác" """
    per = []
    loc = []
    for x in ner(text):
        if "PER" in x[3]:
            per.append(x[0])
        if "LOC" in x[3]:
            loc.append(x[0])
    if len(loc) == 0:
        loc.append("0")
    if len(per) == 0:
        per.append("0")
    return Row("persons", "locations")(",".join(per), ",".join(loc))
Ejemplo n.º 21
0
 def underthesea_annotate(self, text, mode):
     if mode == 'sent_tokenize':
         return sent_tokenize(text)
     elif mode == 'word_tokenize':
         return word_tokenize(text)
     elif mode == 'pos_tag':
         return pos_tag(text)
     elif mode == 'chunk':
         return chunk(text)
     elif mode == 'ner':
         return ner(text)
     elif mode == 'classify':
         return classify(text)
     elif mode == 'sentiment':
         return sentiment(text)
     else:
         raise Exception("Wrong request, please check your request")
def ner_sentence(text):
    entity_key_B = ['B-LOC', 'B-PER', 'B-ORG']
    entity_key_I = ['I-LOC', 'I-PER', 'I-ORG']
    entity_key = ['LOC', 'PER', 'ORG']

    new_text = ''
    entity_merge = ['', -1]  # word_to_merge, position in enity_key

    for pre_word, word, nxt_word in previous_and_next(ner(text)):
        if word[-1] != 'O':
            if (word[-1] in entity_key_I) and (
                    entity_key_I.index(word[-1]) == entity_merge[1]
            ):  # check if entity if I-entity and the same entity type
                entity_merge[0] += word[0] + ' '
            elif word[-1] in entity_key_B:
                entity_merge = [word[0] + ' ', entity_key_B.index(word[-1])]

            if (nxt_word != None):
                # check if next word is I, if true continue
                if (nxt_word[-1] in entity_key_I) and (entity_key_I.index(
                        nxt_word[-1]) == entity_merge[1]):
                    continue
                else:
                    # rstrip to remove space at the end of str
                    new_text += '<' + entity_key[
                        entity_merge[1]] + '>' + entity_merge[0].rstrip(
                        ) + '</' + entity_key[entity_merge[1]] + '> '
                    entity_merge = ['', -1]
                    continue
            else:
                # if next word is None which means there're no word left, concatenate text
                new_text += '<' + entity_key[
                    entity_merge[1]] + '>' + entity_merge[0].rstrip(
                    ) + '</' + entity_key[entity_merge[1]] + '> '
                entity_merge = ['', -1]

        if word[-1] == 'O':
            # check if there're B-entity
            if (entity_merge[0] != ''):
                new_text += '<' + entity_key[
                    entity_merge[1]] + '>' + entity_merge[0].rstrip(
                    ) + '</' + entity_key[entity_merge[1]] + '> '
                entity_merge = ['', -1]
            new_text += word[0] + ' '
    return new_text
Ejemplo n.º 23
0
    def next_State(self, text, product):
        if (check_endProcess(text) or self.isStop(text)):
            return end_state()
        if (self.isContinue(text)):
            return continue_state()
        tokens = vnltk.ner(text)
        N = [token[0] for token in tokens if token[1] in ['N', 'M']]
        product['category'] = object_parse(N)
        product['price'] = price_parse(text)
        product['branch'] = branch_parse(tokens)
        if product['price'] != '' and product['branch'] != '':
            return completeInfo_state()
        if product['price'] != '' and product['branch'] == '':
            return knowCP_state()
        if product['price'] == '' and product['branch'] != '':
            return knowCB_state()

        return knowCategory_state()
Ejemplo n.º 24
0
def _process_question(text):
    res = ner(text)

    # we replace words with entity name
    res_text = ""
    for i, r in enumerate(res):
        entity = r[3]
        sub = r[0]
        if entity == "O":
            res_text += sub + " "
        else:
            if i == len(res) - 1 or i < len(res) - 1 and ( res[i+1][3] == "O" or \
               (entity[:2] == "B-" and len(res[i+1][3]) > 1 and res[i+1][3][:2] == "B-") or \
               (entity != res[i+1][3]) ):
                res_text += "_{}_".format(entity[2:]) + " "
            else:  # skip
                pass

    return res_text.strip()
Ejemplo n.º 25
0
def process_goal_info(text):
    res = {}
    # time_filter = re.compile(r"(\d?\d phút sau)|phút (\d?\d\+?\d)|(\d?\d\+?\d)'")
    time_filter = re.compile(
        r"(\d?\d phút sau)|phút (\d?\d\+?\d)|(\d?\d\+?\d)|(phút thứ \d+)")
    res["time"] = list(
        map(lambda x: [a for a in x if a != ""][0],
            time_filter.findall(text.lower())))

    tagged_sentence = ner(text)
    names = []
    for i, comp in enumerate(tagged_sentence):
        if comp[1] == "Np" and comp[3] == "B-PER":
            names.append(comp[0])
            j = i + 1
            while j < len(
                    tagged_sentence) and tagged_sentence[j][3] == "I-PER":
                names[-1] = names[-1] + " " + tagged_sentence[j][0]
                j += 1
    res["names"] = names
    return res
Ejemplo n.º 26
0
def ner_underthesea(sent):

    entity = []
    res = ner(sent)
    print(res)
    list_token = [x[0] for x in res]
    list_tag_entity = [x[3] for x in res]
    flag = False
    current_entity = []
    for index, x in enumerate(list_tag_entity):
        if x == "B-PER" and flag is False:
            flag = True
            current_entity.append(list_token[index])
            if index + 1 <= len(list_tag_entity) - 1:
                if list_tag_entity[index + 1] != "I-PER":
                    entity_current = " ".join(current_entity)
                    entity.append(entity_current)
                    flag = False
                    current_entity = []
            elif index == len(list_tag_entity) - 1:
                entity_current = " ".join(current_entity)
                entity.append(entity_current)
                flag = False
                current_entity = []

        if x == "I-PER" and flag is True:
            current_entity.append(list_token[index])
            if index + 1 <= len(list_tag_entity) - 1:
                if list_tag_entity[index + 1] != "I-PER":
                    entity_current = " ".join(current_entity)
                    entity.append(entity_current)
                    flag = False
                    current_entity = []
            elif index == len(list_tag_entity) - 1:
                entity_current = " ".join(current_entity)
                entity.append(entity_current)
                flag = False
                current_entity = []

    return entity
Ejemplo n.º 27
0
    def next_State(self, text, product):
        if (check_endProcess(text)):
            return end_state()
        tokens = vnltk.ner(text)
        N = [token[0] for token in tokens if token[1] in ['N', 'M']]
        new_category = object_parse(N)
        if (new_category != [] and new_category != product['category']):
            product['category'] = new_category
            return knowCategory_state()

        querry = self.question_parse(text)
        if (querry != []):
            return ask_state(querry, self.current_product)

        if (self.isNextItem(text)):
            self.current += 5
            return self

        if (self.isBought(tokens)):
            return bought_state()

        return end_state()
Ejemplo n.º 28
0
def create_data(file=None, save_to=None):
    """
    text file to csv file: columns=['SENT#', 'WORD', 'POS', 'CHUNK', 'NER']
    """
    text = ''
    with codecs.open(file, 'r', encoding='utf-8', errors='ignore') as fdata:
        lines = fdata.readlines()
        for line in lines:
            text += line

    df = pd.DataFrame(columns=['SENT#', 'WORD', 'POS', 'CHUNK', 'NER'])
    i = 0
    for sent in underthesea.sent_tokenize(text):
        tdf = pd.DataFrame(underthesea.ner(sent),
                           columns=['WORD', 'POS', 'CHUNK', 'NER'])
        tdf.insert(loc=0, column='SENT#', value=[i] * len(tdf))
        df = df.append(tdf, ignore_index=True)
        i += 1

    df = df.drop(columns=['CHUNK'])
    df.to_csv(save_to, index=False)
    print('saved to ' + save_to)
def underthesea_prc(text):
    pos_tags = pos_tag(text)

    just_ner = ner(text)
    result = {}
    s = ''
    key = ''
    for index, x in enumerate(just_ner):
        ner_label = str(x[3]).split('-')
        if ner_label[0] == 'O' or index == len(just_ner) - 1:
            if s != '':
                if key not in result:
                    result[key] = []
                    result[key].append(s)
                else:
                    result[key].append(s)
                s = ''
        else:
            s = str(x[0])
            key = ner_label[1]
    ner_text = []
    for key, value in result.items():
        a = ''
        a += key + ": "
        value_len = len(value)
        for index, x in enumerate(value):
            a += x
            if index != value_len - 1:
                a += ", "
        ner_text.append(a)

    classify_result = ViUtils.add_accents(
        (classify(text)[0]).replace('_', ' '))

    sentiment_result = sentiment(text)

    return underthesea_text_result(pos_tags, ner_text, classify_result,
                                   sentiment_result)
Ejemplo n.º 30
0
def preprocess_vi(sent):
    entity = [
        chunk[0].lower() for chunk in ner(sent) if chunk[1].startswith('N')
    ]
    result = list(set(entity))
    return result