我有网页的消息来源。它只是大量的随机数字、字母和函数名,在python3中保存为字符串。我想在这个字符串的源代码中找到显示\"followerCount\":的文本,但我也想找到它后面的一些文本(n个字符)。希望能找到我要找的那条短信。我是否可以搜索字符串的一个特定部分,并在中搜索 n 字符,以及在python3中的?
发布于 2021-08-14 01:15:27
使用.find()获得职位:
html = "... lots of html source ..."
position = html.find('"followerCount":')然后使用字符串切片提取字符串的这一部分:
n = 50 # or however many characters you want
print(html[position:position+n])发布于 2021-08-14 01:34:28
一种基于模式查找文本的标准方法是正则表达式。例如,您可以在这里询问"followerCount:“后面的任意三个字符。
import re
s = 'a bunch of randoms_characters/"followerCount":123_more_junk'
match = re.search(r'(?<="followerCount":).{3}', s)
if match:
    print(match.group(0))
    #prints '123'或者,您可以在不需要查找的情况下生成正则表达式,并捕获组中的三个字符:
import re
s = 'a bunch of randoms_characters/"followerCount":123_more_junk'
match = re.search(r'"followerCount":(.{3})', s)
if match:
    print(match.group(1))
    #prints '123'https://stackoverflow.com/questions/68779628
复制相似问题