Как сравнить две строки с дополнительными символами? - PullRequest
0 голосов
/ 18 мая 2019

рассмотрим, что у нас есть функция (в Django || python), которая сравнивает две строки, одна - правильный ответ, а другая - строка ответа ученика.

correct = '(an) apple (device)'
student_answerd = 'apple device'

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

    case 1: an apple device
    case 2: an apple
    case 3: apple device
    case 4: apple

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

Ответы [ 2 ]

2 голосов
/ 18 мая 2019

Может быть, здесь мы могли бы проигнорировать ( и ) и увидеть желаемый результат:

(.*?)(?:[()]|)

RegEx

Если это не было вашим желаемым выражением, вы можете изменить / изменить выражение в regex101.com .

RegEx Circuit

Вы также можете визуализировать свои выражения в jex.im :

enter image description here

JavaScript Demo

const regex = /(.*?)(?:[()]|)/gm;
const str = `(an) apple (device)
apple device`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

Python Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(.*?)(?:[()]|)"

test_str = ("(an) apple (device)\n"
    "apple device")

subst = "\\1"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

RegEx

Если вы хотите буквально проверить правильные ответы, вы можете сделать это слово за словом. Может быть, это выражение будет работать:

^((an|one)?(\s?)([aple]+)?(\s?)([devic]+)?)$

enter image description here

Python Code

Вы можете просто добавить if для совпадения и не совпадать:

# -*- coding: UTF-8 -*-
import re

string = "an apple device"
expression = r'^((an|one)?(\s?)([aple]+)?(\s?)([devic]+)?)$'
match = re.search(expression, string)
if match:
    print("YAAAY! \"" + match.group(1) + "\" is a match ??? ")
else: 
    print('? Sorry! No matches!')

выход

YAAAY! "an apple device" is a match ???

Демонстрация JavaScript для полного соответствия и групп

const regex = /^((an|one)?(\s?)([aple]+)?(\s?)([devic]+)?)$/gm;
const str = `an apple device
an apple
apple device
apple
one apple
one appl device
two apple deive
on apple device
a apple device`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Затем вы можете добавить любые другие символы в список, например, скобки:

^(((one|an)+)?(\s?)([aple()]+)?(\s?)([()devic]+)?)$ 

enter image description here

Это также передало бы некоторые слова с ошибками, которые, я думаю, были бы желательны. Если нет, вы можете просто удалить [] и использовать группы захвата с логическими ИЛИ:

(apple|orange|banana)?
0 голосов
/ 18 мая 2019
"apple" in student_answer #matches 'papple'

или

"apple" in student_answer.split() # doesn't match 'papple'

Кроме того, вы можете заменить обычные добавки.

a = [',', 'an', ' ', 'device']
for i in a:
    student_answer = student_answer.replace(a, '')
student_answer == 'apple'

...