如何随机索引中的句子后随机单词

时间:2017-08-30 02:13:04

标签: python regex string word

这里是String变量

question = "i need to know about something..."

我怎样才能得到"之后我需要知道",如果有时问题变量变化会变成这样:

question = " i need to know about something..." 

question = "hmmm.... i need to know about something"

我的意思是,无论索引在哪里,但我需要知道这句话之后的随机词是什么 - > "我需要知道",在这种情况下,结果将是"某事......"

5 个答案:

答案 0 :(得分:1)

快速而肮脏的解决方案是使用str.strip()。它快速而且脏,因为它不区分大小写,只有在存在确切的字符串时才会起作用

In [22]: "i need to know about something...".split("i need to know about")
Out[22]: ['', ' something...']

In [23]: "hmmm.... i need to know about something".split("i need to know about")
Out[23]: ['hmmm.... ', ' something']

In [24]: "hmmm.... i need to know about  something".split("i need to know about")
Out[24]: ['hmmm.... ', '  something']

In [25]: "hmmm.... i need to know  about something".split("i need to know about")
Out[25]: ['hmmm.... i need to know  about something']

最后一种情况不起作用,因为字符串不完全匹配(注意knowabout之间的2个空格。

正如其他一些答案建议的正则表达式会更加全面

答案 1 :(得分:0)

你可以试试这个:

question = "hmmm.... i need to know about something"

new_data = question[question.index("i need to know about")+len("i need to know about"):]

输出:

something

使用正则表达式:

import re

data = re.findall("(?<=i need to know about)\s[a-zA-Z\s]+", question)

print(data)

输出:

[' something']

答案 2 :(得分:0)

如果它是一个字符串,那么你可以获得你正在寻找的字符串的索引并在此之后得到所有内容,如下所示:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="question[]" placeholder="multipleChoice"><br><br>
<input type="text" id="question[]" placeholder="trueFalse"><br><br>
<input type="text" id="question[]" placeholder="shortAnswer"><br><br>
<input type="text" id="question[]" placeholder="shortAnswer"><br><br>
<input type="text" id="question[]" placeholder="description"><br><br>
<input type="text" id="question[]" placeholder="multipleChoice"><br><br>
<input type="text" id="question[]" placeholder="multipleChoice"><br><br>
<input type="text" id="question[]" placeholder="trueFalse"><br><br>

<span id="result"></span>

答案 3 :(得分:0)

您可以使用正则表达式。

import re
s = "hmmm.... i need to know about something"
regexp = re.compile("i need to know about(.*)$")
print(regexp.search(s).group(1))

输出:

 something

如果要清除输出,可以始终.strip()

print(regexp.search(s).group(1).strip())

输出:

something

答案 4 :(得分:0)

您可以使用正则表达式提取内容,然后我需要了解&#34;。

public IHttpActionResult Get(string category)
{
    try
    {
        // code...

        return Ok(articlesByCategory);
    }
    catch (Exception ex)
    {
        // Something went wrong on our side (NOT the client's fault). So we need to:
        // 1. Log the error so we can troubleshoot it later
        // 2. Let the client know it is not their fault but our fault.
        return InternalServerError();
    }
}
相关问题