【问题标题】:Python Multiline String: How to get the cut based on search valuePython多行字符串:如何根据搜索值获得剪切
【发布时间】:2017-12-10 04:07:34
【问题描述】:

我在运行 Spyder3 的 Python 3 Anaconda 中有如下巨大的文本字符串:

search="germany"

text = "germany's gabriel denies report he is eyeing finmin post
berlin (reuters) - german foreign minister sigmar gabriel on saturday denied 
a report that said the social democrat, whose party has agreed to enter 
talks with chancellor angela merkel's conservatives on forming a coalition, 
was eyeing the post of finance minister.


13.5 hours ago
— reuters





iit-kharagpur gets over 1,000 placement offers in eight days
quantiphi analytics emerged as the largest recruiter of the season till date 
offering 34 jobs, followed by intel at 33
13.5 hours ago
— business standard"

我可以使用以下条件在文本中进行搜索:

if search in text:
    print("Found")
else:
    print("Not Found")

但我真正需要的是获取所有与让我们说“德国”相关的新闻文本,从“德国的 gabriel 否认报告......”一直到“财政部长的职位”,以防在文本中发现德国.

关于如何完成这一壮举有什么想法吗? 提前一千感谢您的所有回答。

【问题讨论】:

  • 将其重述为“我需要获取文本中出现Germany 的每一段”是否正确?如果是这样,也许您可​​以将字符串拆分为"\n\n" 并获取匹配的元素?或下面基于正则表达式的答案。

标签: python string search


【解决方案1】:

是 ez,但您应该阅读有关 regex(正则表达式)的内容,因为我不知道整个数据结构:

import re
search = input("Insert keyword")
text ="............."
if re.search(r'%s(.*?)\n\n'%(search),text,re.DOTALL) == None:
    print("Sorry did't found")
else:
    news = re.search(r'%s(.*?)\n\n'%(search),text,re.DOTALL).group()
    print(news)

【讨论】:

  • 请让我试试。
【解决方案2】:

不要搜索"Germany",而是搜索"German",以涵盖这两种情况。您可能还需要将所有内容转换为小写/大写以搜索任何大小写的子字符串。

你可以先用re.finditer()获取所有的子字符串位置:

import re

search="German"

text = """germany's gabriel denies report he is eyeing finmin postberlin 
(reuters) - german foreign minister sigmar gabriel on saturday denied 
a report that said the social democrat, whose party has agreed to enter 
talks with chancellor angela merkel's conservatives on forming a coalition, 
was eyeing the post of finance minister."""

# converted to lowercase to making searching easier
sub_locs = [s.start() for s in re.finditer(search.lower(), text.lower())]
print(sub_locs)

这将给:

[0, 75]  

然后您可以根据sub_locs 中的索引在text 中切片和添加子字符串:

substrings = []
for start, end in zip(sub_locs[:-1], sub_locs[1:]):
    substrings.append(text[start:end])

# Get last substring
substrings.append(text[end:])

print("GERMAN SUBSTRINGS:")
for i, substr in enumerate(substrings):
    print("{0} -> {1}\n".format(i + 1, substr))

哪些输出:

GERMAN SUBSTRINGS
1 -> germany's gabriel denies report he is eyeing finmin postberlin (reuters) - 

2 -> german foreign minister sigmar gabriel on saturday denied 
a report that said the social democrat, whose party has agreed to enter 
talks with chancellor angela merkel's conservatives on forming a coalition, 
was eyeing the post of finance minister.

【讨论】:

    猜你喜欢
    • 2017-12-14
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    相关资源
    最近更新 更多