Модификация кода для обработки длинного списка строк - PullRequest
1 голос
/ 16 апреля 2020

Я хочу подготовить длинный список данных для задачи. Я был в состоянии собрать код, который выполняет задачу на одном экземпляре, но теперь я хочу, чтобы он запускался через список. Ниже я попробовал.

один экземпляр для тестирования .....

sentences = ['if the stimulus bill had become hamstrung by a filibuster threat or recalcitrant conservadems']
antecedents = ['bill had become hamstrung by']

Фактический вариант использования - это два столбца в pandas кадре данных, которые я преобразовал в списки

f = tra_df['sentence'].tolist()
b = tra_df['antecedent'].tolist()

код для одного варианта использования ....

results =[]

ous = 1
ayx = ' '.join([str(elem) for elem in antecedents])
ayxx = ayx.split(" ")
antlabels = []    
for i in range(len(ayxx)):

    antlabels.append(ous)
    lab = ' '.join([str(elem) for elem in antlabels])



     # Build the regex string required
rx = '({})'.format('|'.join(re.escape(el) for el in antecedents))
     # Generator to yield replaced sentences
it = (re.sub(rx, lab, sentence) for sentence in sentences)
     # Build list of paired new sentences and old to filter out where not the same
results = ([new_sentence for old_sentence, new_sentence in zip(sentences, it) if old_sentence != new_sentence])

# replace other non 1 values with 0
nw_results = ' '.join([str(elem) for elem in results])
ew_results= nw_results.split(" ")
new_results = ['0' if i is not '1' else i for i in ew_results]
labels =([int(e) for e in new_results]) 

labels

И вот в результате я получаю

[0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0]

слегка измененный код для большого списка

for sentences, antecedents in zip(f, b):
    gobels = []
    #def format_labels(antecedents,sentences):
    results =[]
    #lab =[]
    ous = 1
    ayx = ' '.join([str(elem) for elem in antecedents])
    ayxx = ayx.split(" ")
    antlabels = []    
    for i in range(len(ayxx)):
        antlabels.append(ous)
        lab = ' '.join([str(elem) for elem in antlabels])



     # Build the regex string required
    rx = '({})'.format('|'.join(re.escape(el)for el in antecedents))
     # Generator to yield replaced sentences
    it = (re.sub(rx, lab, sentence)for sentence in sentences)
     # Build list of paired new sentences and old to filter out where not the same
    results = ([new_sentence for old_sentence, new_sentence in zip(sentences, it) if old_sentence != new_sentence])

    nw_results = ' '.join([str(elem) for elem in results])
    ew_results= nw_results.split(" ")
    new_results = ['0' if i is not '1' else i for i in ew_results]
    labels =([int(e) for e in new_results]) 

    t2 = time.time()
    gobels.append(labels)

Теперь вместо списка строк, содержащих 0 и 1, я получаю длинный список только из 1 .....

Что может быть не так?

[[1,
  1,
  1,
  1,
  1,
  1,
  1,
  1,
  1,
 ........]

1 Ответ

2 голосов
/ 16 апреля 2020

Нечто подобное может масштабироваться лучше. Вероятно, есть еще способ Pythoni c сделать это до сих пор.

a = '1 2 3 4 5'
b = '3 4 6'

a = a.split()
b = b.split()

for idx, val in enumerate(b):
    try:
        a[a.index(val)] = True
    except ValueError:
        pass

for idx, val in enumerate(a):
    if val is not True:
        a[idx] = False

print([1.0 if i else 0.0 for i in a])
# [0.0, 0.0, 1.0, 1.0, 0.0]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...