Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在一对单引号之间匹配文本_Python_Regex - Fatal编程技术网

Python 在一对单引号之间匹配文本

Python 在一对单引号之间匹配文本,python,regex,Python,Regex,我试图从.txt文件中提取ImageNet标签,如下所示 998: 'ear, spike, capitulum', 999: 'toilet tissue, toilet paper, bathroom tissue'} 提取单引号内的子字符串,但它不断地吐出“无” 我试过在线正则表达式编译器,它运行得非常好。有人能为这个问题提供一些建议吗?主要问题是您应该使用re.search(),而不是re.match()re.match() 明智的做法是使用原始字符串重新填充图案,并且括号过多: imp

我试图从.txt文件中提取ImageNet标签,如下所示

998: 'ear, spike, capitulum', 999: 'toilet tissue, toilet paper, bathroom tissue'} 提取单引号内的子字符串,但它不断地吐出“无”


我试过在线正则表达式编译器,它运行得非常好。有人能为这个问题提供一些建议吗?

主要问题是您应该使用
re.search()
,而不是
re.match()
re.match()

明智的做法是使用原始字符串重新填充图案,并且括号过多:

import re

txt = "998: 'ear, spike, capitulum', 999: 'toilet tissue, toilet paper, bathroom tissue'"

p = re.compile(r"'(.*?)'")
m = p.search(txt)
print(m.groups())
给出:

('ear, spike, capitulum',)
这项工作:

import re
re.findall(r"'(.*?)'", txt)
此正则表达式链接:


并非所有事情都需要通过正则表达式来完成

label = []

with open("imagenet1000_clsid_to_human.txt", 'r', encoding='utf8') as f:
    for line in f:
        parts = line.split("'")
        if len(parts) == 3:
            label.append(parts[1])

旁注:始终打开具有特定编码的文本文件。如果您不确定文件的编码是什么,那么Python也是如此。没有魔法编码检测,您不应该依赖Python的默认值

谢谢你的评论,但仍然不起作用…你需要在正则表达式中转义特殊字符。看看re包中的findall函数。我没有显示所有的.txt文件,但它包含多行!哦,是的。对不起,误读了你的帖子。我会编辑我的答案-findall仍然是您需要的。谢谢!但是
len(parts)==3是从哪里来的呢?我插入它是为了确保只有行被认为正好包含两个单引号,即拆分后正好包含3个部分。明白了!谢谢:D
label = []

with open("imagenet1000_clsid_to_human.txt", 'r', encoding='utf8') as f:
    for line in f:
        parts = line.split("'")
        if len(parts) == 3:
            label.append(parts[1])