回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我试图找到多行文本中所有单词的索引:“print”。但也存在一些问题,这些问题是:</p>
<ol>
<li>如果一行中有两个打印,代码将两次返回单词“print”的相同索引</李>
<li>它无法在同一行中找到第二个“打印”的索引,但会将第一个“打印”的索引打印两次。
我的代码是:</li>
</ol>
<pre class="lang-py prettyprint-override"><code>text = '''print is print as
it is the function an
print is print and not print
'''
text_list = []
for line in text.splitlines():
#'line' represents each line in the multiline string
text_list.append([])
for letter in line:
#Append the letter of each line in a list inside the the text_list
text_list[len(text_list)-1].append(letter)
for line in text_list:
for letter in line:
#check if the letter is after 'p' is 'r' and after that 'i' and then 'n' and at last 't'
if letter == "p":
num = 1
if text_list[text_list.index(line)][line.index(letter)+num] == 'r':
num += 1
if text_list[text_list.index(line)][line.index(letter)+num] == 'i':
num += 1
if text_list[text_list.index(line)][line.index(letter)+num] == 'n':
num += 1
if text_list[text_list.index(line)][line.index(letter)+num] == 't':
num += 1
print(f'index (start,end) = {text_list.index(line)}.{line.index(letter)}, {text_list.index(line)}.{line.index(letter)+num}')
</code></pre>
<p>当我运行它时,会打印:</p>
<pre class="lang-py prettyprint-override"><code>index (start,end) = 0.0, 0.5 #returns the index of the first 'print' in first line
index (start,end) = 0.0, 0.5 #returns the index of the first 'print' in first line instead of the index of the second print
index (start,end) = 2.0, 2.5 #returns the index of the first 'print' in third line
index (start,end) = 2.0, 2.5 #returns the index of the first 'print' in third line instead of the index of the second print
index (start,end) = 2.0, 2.5 #returns the index of the first 'print' in third line instead of the index of the third print
</code></pre>
<p>您可以看到,在结果中,索引是重复的。这是文本列表</strong>:</p>
<pre class="lang-py prettyprint-override"><code>>>> text_list
[['p', 'r', 'i', 'n', 't', ' ', 'i', 's', ' ', 'p', 'r', 'i', 'n', 't', ' ', 'a', 's'],
['i', 't', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 'f', 'u', 'n', 'c', 't', 'i', 'o', 'n', ' ', 'a', 'n'],
['p', 'r', 'i', 'n', 't', ' ', 'i', 's', ' ', 'p', 'r', 'i', 'n', 't', ' ', 'a', 'n', 'd', ' ', 'n', 'o', 't', ' ', 'p', 'r', 'i', 'n', 't']]
>>>
</code></pre>
<p><strong>文本列表中的每个<em>列表</em>都是<strong>文本中的一行。有三行,因此在<strong>文本列表中有三个<em>列表</em>。如何获取第一行中第二个“打印”的索引以及第三行中第二个和第三个“打印”的索引?您可以看到,它只返回第一行和第三行中第一个“print”的索引</p>