我正在尝试编写一个函数,其中输入具有在字符串中多次出现的关键字,并且将打印关键字之后在它们之间有双引号的内容。本质上...
Input= 'alkfjjiekeyword "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee keyword"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness'
Output= someonehelpmepls
itonlygivesmeoneinsteadofmultiple
如果可以将输出作为自己的线路那就更好了。
这是我到目前为止所拥有的:
def getEm(s):
h = s.find('keyword')
if h == -1
return -1
else:
begin = s.find('"',h)
end = s.find('"', begin+1)
result = s[begin +1:end]
print (result)
请不要建议导入。我不知道该怎么做,也不知道它是什么,我是初学者。
最佳答案
让我们看一些示例输入:
>>> Input= 'alkfjjiekeyword "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee keyword"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness'
我认为示例输入中缺少一个 "
,因此我添加了它。
据我了解,您想要获取单词 keyword
后面的双引号中的字符串。如果是这样,那么:
def get_quoted_after_keyword(input):
results = []
split_by_keyword = input.split('keyword')
# you said no results before the keyword
for s in split_by_keyword[1:]:
split_by_quote = s.split('"')
if len(split_by_quote) > 1:
# assuming you want exactly one quoted result per keyword
results.append(split_by_quote[1])
return results
>print('\n'.join(get_quoted_after_keyword(Input))
>someonehelpmepls
>itonlygivesmeoneinsteadofmultiple
它是如何工作的
让我们看第一部分:
>>> Input.split('keyword')
['alkfjjie',
' "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee ',
'"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness']
通过在关键字
上拆分输入
,在本例中我们得到了三个字符串。倒数第二个字符串是单词 keyword
后面的所有字符串。为了获取没有第一个字符串的字符串,我们使用下标:
>>> Input.split('keyword')[1:]
[' "someonehelpmepls"fjioee... omgsos someonerandom help helpppmeeeeeee ',
'"itonlygivesmeoneinsteadofmultiple"... sadnesssadness!sadness']
现在,我们的下一个任务是获取这些字符串中双引号中的部分。为此,我们将每个字符串拆分为 "
。第二个字符串(编号为 1
)将是双引号中的字符串。作为一个更简单的示例,让我们获取这些字符串:
>>> [s.split('"')[1] for s in ('"one"otherstuff', ' "two"morestuff')]
['one', 'two']
接下来,我们将这两个步骤放在一起:
>>> [s.split('"')[1] for s in Input.split('keyword')[1:]]
['someonehelpmepls', 'itonlygivesmeoneinsteadofmultiple']
我们现在有了我们想要的字符串。最后一步是将它们很好地打印出来,每行一个:
>>> print('\n'.join(s.split('"')[1] for s in Input.split('keyword')[1:]))
someonehelpmepls
itonlygivesmeoneinsteadofmultiple
限制:此方法假设关键字
永远不会出现在双引号字符串内。
关于python - 打印字符串中多次出现的情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39671016/