我有一个很长的文本文件,我试图将某些字符串拉出来。这些字符串的长度随文本文件而变化,但始终位于某些标识符之后。例如,假设我的文本文件如下所示:
垃圾文字......
名称:
年龄:
罗伯特
20
4。
垃圾文字......
我总是知道“罗伯特”字符串位于“年龄:\ n \ n”但我不确定它只会以“\ n \ n”结束并且与“二十四”。串。我尝试过使用
namepos1 = string.find(“年龄:”)
namepos2 = namepos1 + 6
这将给出我想要的字符串的起始位置,但我不知道如何将其保存到变量中,以便始终将整个字符串保存到两个新行字符。如果它是一个设定长度而不是变量我想我可以使用:
name = string [namepos2:length]
但任何帮助将不胜感激。我可能不得不完全不同,但这是我考虑过它的第一种方式,并试图这样做 谢谢!
答案 0 :(得分:0)
你可以通过找到年龄来做到这一点,然后如果你想这样做,那么你可以将你的光标向前移动两行,如果你想要在" junk"之后的整个文本部分,你知道多长时间该文本是,这也可以:
lookup = 'age'
lines=[]
with open('C:/Users/Luke/Desktop/Summer 2016/Programs/untitled5.txt') as myFile:
for num, line in enumerate(myFile, 1):
if lookup in line:
lines.append(num+2)
ofile=open('C:/Users/Luke/Desktop/Summer 2016/Programs/untitled5.txt')
line=ofile.readlines()
interestinglines=''
for i in range(len(lines)):
interestinglines+=(line[lines[i]]+'\n')
你可能需要修改一下,但我相信这应该会重现你正在寻找的东西。 '\n'
已添加到line[lines[i]]
,以便您将其保存到新文件中。
答案 1 :(得分:0)
在字符串中找到位置后,您可以通过\ n \ n拆分字符串并获取第一项。
$(function() {
$("#smart-form").steps( {
bodyTag:"fieldset", headerTag:"h2", bodyTag:"fieldset", transitionEffect:"slideLeft", titleTemplate:"<span class='number'>#index#</span> #title#", labels: {
finish: "Send søknad", next: "Neste", previous: "Tilbake", loading: "Laster..."
}
, onStepChanging:function(event, currentIndex, newIndex) {
if(currentIndex>newIndex) {
return true;
}
var form=$(this);
if(currentIndex<newIndex) {}
return form.valid();
}
, onStepChanged:function(event, currentIndex, priorIndex) {}
, onFinishing:function(event, currentIndex) {
var form=$(this);
form.validate().settings.ignore=":disabled";
return form.valid();
}
, onFinished:function(event, currentIndex) {
var form=$(this);
$(form).ajaxSubmit( {
target:'.result', beforeSubmit:function() {}
, error:function() {}
, success:function() {
$('.alert-success').show().delay(7000).fadeOut();
$('.field').removeClass("state-error, state-success");
if($('.alert-error').length==0) {
$('#smart-form').resetForm();
reloadCaptcha();
}
}
}
);
}
}