【发布时间】:2016-05-12 18:00:38
【问题描述】:
***********************************解决方案*********** *****************
经过大量测试和一些调整后,我已经成功编写了一个工作代码!
我与大家分享它,以防有人有兴趣执行与我相同的事情。 感谢所有帮助过的人——谢谢! :)
stringToSearchIn = open('FileName.py').read()
def findBetween(file, firststring, laststring, findstring):
start = 0
countfinal = 0
while True:
try:
start = file.index(firststring, start)
except:
break
try:
end = file.index(laststring, start)
count = file[start:end].count(findstring)
countfinal = count + countfinal
start = end
except:
break
return countfinal
print findBetween(stringToSearchIn, "example", "file", "letters")
*********************************结束解决方案************ ***************
我已经尝试解决这个问题很长一段时间了,我相信我的想法过于复杂。 对我来说写起来有点复杂,但我会尽力而为。如果有不清楚的地方,请随时提问!
请不要为我编写代码。我是来学习的,不是来抄袭的:)
例如:
#This is the entire text I want to scan
s = open('test.py').read()
#I want to go through the entire file and find the string between these two strings:
stringStartToSearch = "example"
stringEndToSearch = "file"
#Next, I want to count the number of times a certain string is located
#between the previously found string.
stringSearch = "letters"
为了进一步澄清,假设这是在“test.py”文件中找到的字符串:
#An example text that I have many letters in, just to give and example for a file.
#It's an example with many letters that I made especially for this file test.
#And these are many letters which should not be counted
如您所见,“字母”一词在此文件中出现了 3 次,但在“示例”和“文件”之间仅出现 2 次strong>。这就是我要数的。
有没有人知道一种有效的pythonic方法来实现这一点?
非常感谢!
为您服务
脚本确实在 2 个给定的字符串之间找到了正确的字符串,但是在找到它之后就停止了。我需要它继续搜索整个文件,而不是在找到后停止。 另外,在我找到这两个字符串之间的字符串之后,我需要遍历它并计算某个单词显示的次数。用什么命令可以实现?
file = open('testfile.py').read()
def findBetween(file, firstWord, secondWord):
start = file.index(firstWord)+len(firstWord)
end = file.index(secondWord, start)
return file[start:end]
print findBetween(file, "example", "file")
【问题讨论】:
-
签出string.find() 和字符串切片将是一个好的开始。
-
另外,如果文本中有连续的示例或文件怎么办?我的意思是
... example ... letter ... example ... letter ... file ... -
如果测试字符串为
example something file letters file,结果应该是什么? -
@Lafexlos - 会有连续的示例和文件,我想计算在它们之间找到“字母”的所有时间。
-
所以你想得到第一个
example和最后一个file之间的所有letters?
标签: python string file python-3.x find