Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.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_Indexing - Fatal编程技术网

Python 查找字符串的索引号

Python 查找字符串的索引号,python,indexing,Python,Indexing,我正在用python创建一个程序,它将遍历一系列句子,并在句子中找到大写的单词。我现在用芬德尔函数来获取资本 以下是我目前收到的输出示例: line 0: the dog_SUBJ bit_VERB the cat_OBJ ['S'] ['U'] ['B'] ['J'] [] ['V'] ['E'] ['R'] ['B'] [] ['O'] ['B'] ['J'] 但是,我希望输出为完整单词,如下所示: ['SUBJ'] [] ['VERB'] [] ['OBJ'] 我还希望单词的索引如下

我正在用python创建一个程序,它将遍历一系列句子,并在句子中找到大写的单词。我现在用芬德尔函数来获取资本

以下是我目前收到的输出示例:

line 0: the dog_SUBJ bit_VERB the cat_OBJ
['S'] ['U'] ['B'] ['J'] [] ['V'] ['E'] ['R'] ['B'] [] ['O'] ['B'] ['J'] 
但是,我希望输出为完整单词,如下所示:

['SUBJ'] [] ['VERB'] [] ['OBJ']
我还希望单词的索引如下:

['SUBJ'] [0]
['VERB'] [1]
['OBJ'] [2]
有可能这样做吗?我以前在终端上看到过上述操作,我认为使用了“索引”或类似的东西

以下是我的代码(据我所知):

谢谢!任何帮助都将不胜感激

类似于:

>>> s = 'the dog_SUBJ bit_VERB the cat_OBJ'
>>> import re
>>> from itertools import count
>>> zip(re.findall('[A-Z]+', s), count())
[('SUBJ', 0), ('VERB', 1), ('OBJ', 2)]

适当格式化…

无需使用itertools:
list(enumerate(re.findall('[A-Z]+',s))
@root-yup-如果OP要格式化元组,那么索引在哪个位置实际上并不重要…对@root的代码稍加修改:
list(enumerate([x[1:]表示re.findall('[A-Z]+',l])
)。现在可以使用“thedog\u SUBJ bit\u动词Cat\u OBJ”和类似的工具。@ejrb切片不是必需的-只需将
\ucode>作为非捕获和捕获组其余:
(?:))([A-Z]+)
@ejrb是的-不是100%确定我为什么现在把非捕获放在那里,但不管怎样,我们之间我想我们到了那里;)小心,因为正则表达式将匹配专有名词/句子开头等的大写字母。为确保健壮性,我还将匹配下划线
m=re.findall(“[A-Z]+”,string)
。通过字符串切片
m=[x[1:]对于m中的x]
>>> s = 'the dog_SUBJ bit_VERB the cat_OBJ'
>>> import re
>>> from itertools import count
>>> zip(re.findall('[A-Z]+', s), count())
[('SUBJ', 0), ('VERB', 1), ('OBJ', 2)]