Предварительная обработка, чтобы избавиться не от дефиса, а от da sh в предложениях - PullRequest
0 голосов
/ 02 августа 2020

Что бы я хотел сделать

Я бы хотел избавиться не от дефиса, а от da sh в предложениях для предварительной обработки NLP.

Input

samples = [
    'A former employee of the accused company, ———, offered a statement off the record.', #three dashes
    'He is afraid of two things — spiders and senior prom.' #dash
    'Fifty-six bottles of pop on the wall, fifty-six bottles of pop.' #hyphen
]

Ожидаемый результат

#output
['A former employee of the accused company','offered a statement off the record.']
['He is afraid of two things', 'spiders and senior prom.']
['Fifty-six bottles of pop on the wall', 'fifty-six bottles of pop.']

Приведенные выше предложения взяты из следующих двух статей о дефисах и da sh.

Проблема

  1. Первый процесс, от которого нужно избавиться символ '-' не удалось, и трудно понять причину, по которой второе и третье предложения были объединены без одинарных кавычек ('').
#output
['A former employee of the accused company, — — —, offered a statement off the record.', 
'He is afraid of two things—spiders and senior prom.
Fifty-six bottles of pop on the wall, fifty-six bottles of pop.']
Понятия не имею, как я могу написать код, чтобы различать guish дефис и sh.

Текущий код

samples = [
    'A former employee of the accused company, — — —, offered a statement off the record.', #dash
    'He is afraid of two things—spiders and senior prom.' #dash
    'Fifty-six bottles of pop on the wall, fifty-six bottles of pop.' #hyphen
]

ignore_symbol = ['-']
for i in range(len(samples)):
    text = samples[i]
    ret = []
    for word in text.split(' '):
        ignore = len(word) <= 0 
        for iw in ignore_symbol:
            if word == iw:
                ignore = True
                break
        if not ignore:
            ret.append(word)

    text = ' '.join(ret)
    samples[i] = text
print(samples)

#output
['A former employee of the accused company, — — —, offered a statement off the record.', 
'He is afraid of two things—spiders and senior prom.
Fifty-six bottles of pop on the wall, fifty-six bottles of pop.']

for i in range (len(samples)):
    list_temp = []
    text = samples[i]
    list_temp.extend([x.strip() for x in text.split(',') if not x.strip() == ''])
    samples[i] = list_temp
print(samples)

#output
[['A former employee of the accused company',
  '— — —',
  'offered a statement off the record.'],
 ['He is afraid of two things—spiders and senior prom.Fifty-six bottles of pop on the wall',
  'fifty-six bottles of pop.']]

Среда разработки

Python 3.7.0

Ответы [ 3 ]

2 голосов
/ 02 августа 2020

Если вы ищете решение без регулярных выражений, точка Unicode для da sh равна 8212, поэтому вы можете заменить их на ',', затем разделить на ',' и затем добавить предложения без пробелов:

>>> samples = [
    'A former employee of the accused company, ———, offered a statement off the record.', #three dashes
    'He is afraid of two things — spiders and senior prom.', #dash
    'Fifty-six bottles of pop on the wall, fifty-six bottles of pop.' #hyphen
]
>>> output = [[
               sentence.strip() for sentence in elem.replace(chr(8212), ',').split(',') 
               if sentence.strip()
              ] for elem in samples]
>>> output
[['A former employee of the accused company',
  'offered a statement off the record.'],
 ['He is afraid of two things', 'spiders and senior prom.'],
 ['Fifty-six bottles of pop on the wall', 'fifty-six bottles of pop.']]
1 голос
/ 02 августа 2020

Прежде всего, 2-е и 3-е предложение были объединены, потому что нет запятой, разделяющей обе строки. В Python запись tmp = 'a''b' эквивалентна tmp = 'ab', поэтому в samples всего 2 строки (2-я и 3-я объединены).

К вашему вопросу: Функция remove_dash_preserve_hyphen ниже удаляет все дефисы в параметре str_sentence и возвращает очищенный str_sentence. Затем функция применяется ко всем строковым элементам в списке samples, генерируя таким образом чистый samples_without_dash.

samples = [
    'A former employee of the accused company, ———, offered a statement off the record.', #three dashes
    'He is afraid of two things — spiders and senior prom.',#**(COMMA HERE)** #dash
    'Fifty-six bottles of pop on the wall, fifty-six bottles of pop.' #hyphen
]

def remove_dash_preserve_hyphen(str_sentence, dash_signatures=['—']):
    for dash_sig in dash_signatures:
        str_sentence = str_sentence.replace(dash_sig, '')
    return str_sentence

samples_without_dash = [remove_dash_preserve_hyphen(sentence) for sentence in samples]

Точное значение da sh, о котором идет речь, - это 'em-da sh 'с юникодом' U + 2014 '. Возможно, в сэмплах будет больше штрихов, которые вам не нужны. Вам нужно отследить его выборочно и передать список всех типов da sh (тех, которые вам не нужны) в параметре dash_signatures при вызове функции remove_dash_preserve_hyphen.

0 голосов
/ 02 августа 2020

Попытка использовать регулярное выражение (регулярное выражение), разделенное на re.split. Функция Python String.split () слишком ограничена для этого. Затем вам нужно будет передать версию Unicode символа «дефиса».

Что-то вроде:

re.split('[\002D]', text)
...