在字典中查找两个字符之间的字符串
Find string between two characters inside of dict
你能找到字符之间的子串吗 我想找到这个字符svm
?
我看了 and Find string between two substrings。所以这是我的字符串 ('svm', SVC())
我想找到 ' '
之间的所有内容所以结果应该是 svm
或 dct_test
import re
dict_SupportVectorMachine = {
"classifier": ('svm', SVC()),
"parameters": {'svm__C':[0.001,0.01,0.1,10, 100],
'svm__gamma':[0.1,0.01],
'svm__kernel':['linear', 'sigmoid']}
}
string = dict_SupportVectorMachine['classifier']
string2 = ('dct_test', ThisCouldbeLongerAndShorter())
subStr = re.findall(r"('(.+?)',",string)
print(subStr)
[OUT]
error: missing ), unterminated subpattern at position 0
第四行好像漏了一个)
:
import re
string = "('svm', SVC())"
string2 = "('dct_test', ThisCouldbeLongerAndShorter()))"
subStr = re.findall(r"('(.+?))',",string)
print(subStr)
您拥有的是一个包含 2 个元素的 tuple
:一个 str
和一个 SVC
实例,只需获取第一个索引
dict_SupportVectorMachine = {
"classifier": ('svm', SVC()),
"parameters": {}
}
classif = dict_SupportVectorMachine['classifier']
print(classif[0]) # svm
由于问题不同,旧答案
括号是用于构建组的特殊字符,对于真正的括号你需要转义它\(
。在此处也使用 search
而不是 findall
import re
string = "('svm', SVC())"
print(re.findall(r"\('(.+?)',", string)) # ['svm']
print(re.search(r"\('(.+?)',", string).group(1)) # svm
string2 = "('dct_test', ThisCouldbeLongerAndShorter()))"
print(re.findall(r"\('(.+?)',", string2)) # ['dct_test']
print(re.search(r"\('(.+?)',", string2).group(1)) # dct_test
你能找到字符之间的子串吗 我想找到这个字符svm
?
我看了('svm', SVC())
我想找到 ' '
之间的所有内容所以结果应该是 svm
或 dct_test
import re
dict_SupportVectorMachine = {
"classifier": ('svm', SVC()),
"parameters": {'svm__C':[0.001,0.01,0.1,10, 100],
'svm__gamma':[0.1,0.01],
'svm__kernel':['linear', 'sigmoid']}
}
string = dict_SupportVectorMachine['classifier']
string2 = ('dct_test', ThisCouldbeLongerAndShorter())
subStr = re.findall(r"('(.+?)',",string)
print(subStr)
[OUT]
error: missing ), unterminated subpattern at position 0
第四行好像漏了一个)
:
import re
string = "('svm', SVC())"
string2 = "('dct_test', ThisCouldbeLongerAndShorter()))"
subStr = re.findall(r"('(.+?))',",string)
print(subStr)
您拥有的是一个包含 2 个元素的 tuple
:一个 str
和一个 SVC
实例,只需获取第一个索引
dict_SupportVectorMachine = {
"classifier": ('svm', SVC()),
"parameters": {}
}
classif = dict_SupportVectorMachine['classifier']
print(classif[0]) # svm
由于问题不同,旧答案
括号是用于构建组的特殊字符,对于真正的括号你需要转义它\(
。在此处也使用 search
而不是 findall
import re
string = "('svm', SVC())"
print(re.findall(r"\('(.+?)',", string)) # ['svm']
print(re.search(r"\('(.+?)',", string).group(1)) # svm
string2 = "('dct_test', ThisCouldbeLongerAndShorter()))"
print(re.findall(r"\('(.+?)',", string2)) # ['dct_test']
print(re.search(r"\('(.+?)',", string2).group(1)) # dct_test