【问题标题】:Is there a way to substring, which is between two words in the string in Python?有没有办法在 Python 中的字符串中的两个单词之间进行子字符串化?
【发布时间】:2017-07-14 10:30:41
【问题描述】:

我的问题或多或少类似于: Is there a way to substring a string in Python? 但它更具体。 如何获得位于初始字符串中两个已知单词之间的字符串的 par。

例子:

mySrting = "this is the initial string"
Substring = "initial"

知道“the”和“string”是字符串中可以用来获取子字符串的两个已知单词。

谢谢!

【问题讨论】:

  • 所以你想要两个已知单词之间的字符串?为什么空格不是Substring 的一部分?
  • 此外,如果'the''string'mySrting 中出现多次会发生什么?
  • @WillemVanOnsem 那么它可能应该显示一个字符串列表。
  • @WillemVanOnsem 和空格可以包含在另外两个词'the'和'string'中

标签: string python-3.x substring


【解决方案1】:

您可以从这里开始简单的字符串操作。 str.index 是你最好的朋友,因为它会告诉你子字符串在字符串中的位置;您也可以稍后在字符串中的某个位置开始搜索:

>>> myString = "this is the initial string"
>>> myString.index('the')
8
>>> myString.index('string', 8)
20

查看切片[8:20],我们已经接近我们想要的:

>>> myString[8:20]
'the initial '

当然,既然我们找到了'the'的起始位置,我们需要考虑它的长度。最后,我们可能想要去掉空格:

>>> myString[8 + 3:20]
' initial '
>>> myString[8 + 3:20].strip()
'initial'

结合起来,你会这样做:

startIndex = myString.index('the')
substring = myString[startIndex + 3 : myString.index('string', startIndex)].strip()

如果您想多次查找匹配项,那么您只需要重复执行此操作,同时仅查看字符串的其余部分。由于str.index 只会找到第一个匹配项,因此您可以使用它来非常有效地扫描字符串:

searchString = 'this is the initial string but I added the relevant string pair a few more times into the search string.'
startWord = 'the'
endWord = 'string'
results = []

index = 0
while True:
    try:
        startIndex = searchString.index(startWord, index)
        endIndex = searchString.index(endWord, startIndex)

        results.append(searchString[startIndex + len(startWord):endIndex].strip())

        # move the index to the end
        index = endIndex + len(endWord)

    except ValueError:
        # str.index raises a ValueError if there is no match; in that
        # case we know that we’re done looking at the string, so we can
        # break out of the loop
        break

print(results)
# ['initial', 'relevant', 'search']

【讨论】:

    【解决方案2】:

    你也可以试试这样的:

    mystring = "this is the initial string"
        mystring = mystring.strip().split(" ")
        for i in range(1,len(mystring)-1):
            if(mystring[i-1] == "the" and mystring[i+1] == "string"):
                print(mystring[i])
    

    【讨论】:

      【解决方案3】:

      我建议结合使用list, splitjoin 方法。 如果您在子字符串中查找超过 1 个单词,这应该会有所帮助。

      1. 将字符串转为数组:

        words = list(string.split())

      2. 获取开始和结束标记的索引,然后返回子字符串:

        open = words.index('the') close = words.index('string') substring = ''.join(words[open+1:close])

      在继续之前,您可能希望通过检查有效性来做一些改进。


      如果您的问题变得更复杂,即对值多次出现,我建议使用正则表达式。

      import re substring = ''.join(re.findall(r'the (.+?) string', string))

      如果您在list 中查看子字符串,re 应该单独存储子字符串。

      我使用描述之间的空格来排除单词之间的空格,您也可以根据需要进行修改。

      【讨论】:

        猜你喜欢
        • 2013-12-12
        • 2014-05-28
        • 2021-01-04
        • 1970-01-01
        • 1970-01-01
        • 2021-10-04
        • 2020-04-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多