1

Для анализа текста мы преобразуем его в список слов P1 . Затем применяем методы bigram и получаем список X пар слов (ai,bi), таких, что ai и bi встречаются в P1 один за другим в тексте много раз. Как получить в Python 3 список P2 из P1 так что каждые два элемента ai и bi, если они идут один за другим в P1 и (ai,bi) принадлежит X, будут заменены на один элемент ai_bi? У меня есть свой код, надеялся, что есть более быстрые приемы.

import nltk
from nltk.collocations import *
import re
import gensim
bigram_measures = nltk.collocations.BigramAssocMeasures()
sentences=["Total internal reflection ! is the;phenomenon",
"Abrasive flow machining :is an ? ( interior surface finishing process)",
"Technical Data[of Electrical Discharge wire cutting and] Cutting Machine",
"The greenhouse effect. is the process by which, radiation from a {planet atmosphere warms }the planet surface",
"Absolute zero!is the lowest limit ;of the thermodynamic temperature scale:",
"The term greenhouse effect ?is mentioned (a lot)",
"[An interesting] effect known as total internal reflection.",
"effect on impact energies ,Electrical discharge wire cutting of ADI",
"{Absolute zero represents} the coldest possible temperature",
"total internal reflection at an air water interface",
"What is Electrical Discharge wire cutting Machining and how does it work",
"Colder than Absolute Zero",
"A Mathematical Model for  Electrical Discharge Wire Cutting Machine Parameters"]
P1=[]
for f in sentences:
    f1=gensim.utils.simple_preprocess (f.lower())
    P1.extend(f1)
print("First 100 items from P1")
print(P1[:100])
#  bigram
finder = BigramCollocationFinder.from_words(P1)
# filter only bigrams that appear 2+ times
finder.apply_freq_filter(2)
# return the all bi-grams with the highest PMI
X=finder.nbest(bigram_measures.pmi, 10000)
print()
print("Number of bigrams= ",len(X))
print("10 first bigrams with the highest PMI")
print(X[:10])
# replace ai and bi which are one after another in P1  and (ai,bi) in X  =>>  with ai_bi
P2=[]
n=len(P1)
i=0
while i<n:
    P2.append(P1[i])
    if i<n-2:
        for c in X:
            if c[0]==P1[i] and c[1]==P1[i+1]:
                P2[len(P2)-1]=c[0]+"_"+c[1]
                i+=1    # skip second item of couple from X  
                break
    i+=1
print()
print( "first 50 items from P2 - results")
print(P2[:50])
0

2 ответа 2

2

Было бы неплохо, если бы автор попытался решить задачу сам, но мне она показалось любопытной:

def foo(a, b):
    if not a:
        return []
    it = iter(a)
    curr = next(it)
    res = []
    while True:
        try:
            next_ = next(it)
            if (curr, next_) in b:
                res.append('{}_{}'.format(curr, next_))
                curr = next(it)
            else:
                res.append(curr)
                curr = next_
        except StopIteration:
            return res

P1 = (1, 2, 1, 2, 3, 4, 1, 2, 3, 3, 4)
X = ((1, 2), (3, 4))
print(foo(P1, X))  # ['1_2', '1_2', '3_4', '1_2', 3, '3_4']
1
  • При P1 = (1,), X = () отработает неправильно. В общем, забывает последний элемент, если он не в паре. Можно решить через itertools.groupby, хоть и не совсем очевидным способом.
    – extrn
    2 апр 2019 в 9:47
1

Решение, которое я упоминал в комментариях. Не совсем очевидное, но быстрое и вроде бы вполне читаемое.

from functools import cmp_to_key
from itertools import groupby

def collapse_bigrams(words, bigrams):
    @cmp_to_key
    def cmp(i, j):
        return 0 if i + 1 == j and (words[i], words[j]) in bigrams else -1

    return ['_'.join(words[i] for i in group)
            for _, group in groupby(range(len(words)), key=cmp)]

P2 = collapse_bigrams(P1, set(X))

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.