Str.find公司()无法搜索“\n”

2024-03-29 11:17:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用str.find()在两个关键字之间提取文本。但找不到'\n'

text = 'Cardiff, the 6th November 2007\n company \n'
String_to_extract = '6th November 2007'
keywords = {'date': ['Cardiff, the ' , '\n']}

代码:

text2=text[text.find(keywords['date']0])+len(keywords[0]):text.find(keywords['date'][1])]
print(text2)

str.find() is unable to search for '\n', which results in no output

PS只想使用str.find()方法


Tags: thetotext文本datestringextract关键字
3条回答

你错误地计算了第一个索引。试试这个:

text = 'Cardiff, the 6th November 2007\n\n company \n\n'
keywords = ['Cardiff, the ', '\n']

result = text[text.find(keywords[0])+len(keywords[0]):text.find(keywords[1])]

输出:

6th November 2007

概括答案。使用此代码:

text2 = text[text.find(keywords[key][0])+len(keywords[key][0]):text.find(keywords[key][1])] # you can replace the key with whatever you want as keys

这里有几个问题:

  • keywords字典中,使用的date变量应该是string:'date'。你知道吗
  • keywords字典中,您对\\n进行了双重转义,而在text变量中不执行此操作。你知道吗
  • 在索引计算中,使用定义为no where的key变量;这应该是keywords字典中定义的'date'键。你知道吗
  • 最后,计算第一个索引的起始位置,而它应该是结束位置。你知道吗

试试这个:

# String to be extracted = '6th November 2007'
text = 'Cardiff, the 6th November 2007\n\n \n\n'
keywords = {'date' : ['Cardiff, the ' , '\n\n']}

a = text.find(keywords['date'][0]) + len(keywords['date'][0])
b = text.find(keywords['date'][1])
text2 = text[a:b]
print(text2)

相关问题 更多 >