【问题标题】:Extract text from string when begining and ending words are given in python在python中给出开始和结束词时从字符串中提取文本
【发布时间】:2017-05-28 15:01:37
【问题描述】:

当给出开始和结束字符串时,如何从字符串中提取文本?

s = "Waiting is a 2015 Indian comedy-drama film directed by Anu Menon, released in India on 27 May 2016. Produced by Priti Gupta of Ishka Films and Manish Mundra of Drishyam Films, the film was co-written by Menon and James Ruzicka"

begining = "Produced"
ending = "Films" 

输出应该是:

由 Ishka Films 的 Priti Gupta 和 Drishyam Films 的 Manish Mundra 制作

【问题讨论】:

  • 将字符串命名为str 是个坏主意,因为这会影响内置的str() 方法。我知道你发布的只是一个例子,我想我会指出这一点,以防你不知道:-)
  • 对不起,我急着问这个问题。

标签: python string


【解决方案1】:

使用str.findstr.rfind 函数的解决方案带有额外的检查(确保找到两个单词):

s = "Waiting is a 2015 Indian comedy-drama film directed by Anu Menon, released in India on 27 May 2016. Produced by Priti Gupta of Ishka Films and Manish Mundra of Drishyam Films, the film was co-written by Menon and James Ruzicka"
begining_str = "Produced"
ending_str = "Films"

b_pos = s.find(begining_str)
e_pos = s.rfind(ending_str)
result = s[b_pos:e_pos + len(ending_str)] if b_pos != -1 and e_pos != -1 else ''

print(result)

输出:

Produced by Priti Gupta of Ishka Films and Manish Mundra of Drishyam Films

【讨论】:

  • 我遇到了一个问题。如果我有重复的单词怎么办?
  • @BharathShetty,那么,您应该定义搜索规则。
  • link。这就是我遇到的问题。
  • @BharathShetty,您可以使用新问题发起新问题
【解决方案2】:

可以利用python中字符串的index方法,使用切片。

对于您的特定示例,这样的事情应该可以工作:

s[s.index(b):s.index(e)+len(e)]

以上代码的作用如下:s.index(b)b 中查找字符串左侧的第一个匹配项。类似s.index(e)。由于您还想包含结束词,我们只需将结束字符串中的字符数添加到最后一个索引。 s[x:y] 为您提供从 x 到 y 的字符串“切片”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 2015-08-03
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 2017-04-28
    相关资源
    最近更新 更多