Python:对于一个长字符串,其中某个单词是重复的,如何识别该单词在唯一单词之后的第一次出现?

5hcedyr0  于 2024-01-05  发布在  Python
关注(0)|答案(1)|浏览(156)

我有一个由许多数据块组成的大文件。例如,两个数据块如下所示:

  1. name1 1234567 comment
  2. property1 = 1234567.98765 property2 = 1234567.98765
  3. property3 = 1234567.98765
  4. final
  5. name2 1234568 comment
  6. property1 = 987654.321 property2 = 9876543.0
  7. property3 = 1234567.98765
  8. final
  9. ...

字符串

问题,我有一段代码修改了一个数据块,但是代码的结果是一个字符串(updated_string),其中包含了文件中的所有数据块(修改的数据块和所有其他未修改的数据块)。
Goal.我只想要updated_string中修改后的数据块,然后只将updated_string放在外部文件中,文件中的所有其他数据块都保持不变。

到目前为止,我已经从以前的帖子中找到了如何从updated_string中删除修改后的数据块之前的所有内容。例如,如果第二个数据块已经被修改,我会这样做:

  1. mystring = "name2"
  2. begin = string.find(mystring)
  3. string[:begin]


但是,我无法删除我想要的数据块中“final“之后的所有内容。我知道我可以这样做

  1. mystring2 = "final"
  2. stop = string.find(mystring2)
  3. string[stop:]


但是它并没有标识出我想要的特定数据块,有没有人可以建议我如何查找name2之后的第一个“final”,这样我就可以得到一个只由我想要的数据块组成的字符串?

xxb16uws

xxb16uws1#

逻辑并不完全清楚,但假设你想找到name2和它后面的第一个final之间的块,只要调整你当前的逻辑就可以了:

  1. mystring = "name2"
  2. begin = string.find(mystring)
  3. string = string[begin:] # we drop all before mystring
  4. mystring2 = "final"
  5. stop = string.find(mystring2) # now we find the stop in the new string
  6. string = string[:stop+len(mystring2)]

字符串
或者,更好的方法是使用str.findstart参数:

  1. mystring = "name2"
  2. begin = string.find(mystring)
  3. mystring2 = "final"
  4. # now we only search the stop word after
  5. # the position of the start word (+ its length)
  6. stop = string.find(mystring2, begin+len(mystring))
  7. out = string[begin:stop+len(mystring2)]


输出量:

  1. name2 1234568 comment
  2. property1 = 987654.321 property2 = 9876543.0
  3. property3 = 1234567.98765
  4. final

展开查看全部

相关问题