说我要填一个句子
sentence_to_fill = "I have 4 {{fruit}}"
我有这样的字典
my_dict = { "fruit": ["apple", "banana", "pear"] }
我希望看到这样的输入:
Input: "I have 4 apple"
Output: True, "apple"
如果匹配python中dict中的一个值,则只返回带有水果的True。
最简单,最有效的方法是什么?
答案 0 :(得分:1)
如果您可以控制sentence_to_fill
的格式并且可以改为I have 4 {fruit}
,那么您可以利用**kwargs
和format()
代替这些或正则表达式:
def test_fruit_sentence(sentence):
template = "I have 4 {fruit}"
valid_values = {"fruit": ["apple", "banana", "pear"]}
for key, values in valid_values.items():
for value in values:
generated_sentence = template.format(**{key: value})
if generated_sentence == sentence:
return True, value
return False, None
result = test_fruit_sentence("I have 4 apple")
print(result)
答案 1 :(得分:0)
使用正则表达式进行匹配。
public T remove(int givenPosition)
{
T dataToReturn;
if (givenPosition < 0 || givenPosition >= manyNodes)
{
return null;
}
if (givenPosition == 0)
{
dataToReturn = head.getData();
head = head.getLink();
}
else
{
Node<T> previous = head;
for (int i = 0; i < givenPosition - 1; i++)
{
previous = previous.getLink();
}
Node<T> oneToDelete = previous.getLink();
dataToReturn = oneToDelete.getData();
previous.setLink(oneToDelete.getLink());
oneToDelete.setLink(null);
}
manyNodes--;
return dataToReturn;
}
答案 2 :(得分:0)
您可以使用正则表达式进行搜索,并使用Python的read_coordinate(C) :-
write('type the position of move you want to make as a coordinate:'),
C is point(X,Y),
read(C).
%some code for point
point(X,Y):- ...
关键字来检查字典中的成员资格。
re.search将搜索{{...}}模式,group(1)选择花括号内的文本,然后您可以检查提供的字典中的成员资格。
in