我有一个文本文件,格式如下:
<a id="atrigger1" class="btn btn-primary disabled"
href=".modalPseudoClass" data-toggle="modal">Bid!</a>
我想在这个文本文件中搜索&#34; true&#34;的运行条件。并且空闲时间大于设定值(例如10)。一旦满足这个条件,我想打印整行。我怎么能得到这个?目前的代码是:
------------------------------------------------------------
Name=A Run=true Idle=15
Name=B Run=true Idle=10
Name=C Run=false Idle=75
Name=D Run=true Idle=92
Name=E Run=false Idle=6
Name=F Run=false Idle=21
-------------------------------------------------------------
答案 0 :(得分:1)
这应该做:
def main():
with open('data.txt', 'r') as searchfile:
for line in searchfile:
line = line.strip()
# This works because Python checks this substring in the line
if ("Run=true") in line:
firstSplit = line.split("Idle=")[1]
# Splitting again to get the first element before the whitespace
idleNum = int(firstSplit.split('\s')[0])
# This had to be changed as you are comparing integers while
# the data is still of type string
if (idleNum >=10):
print line
if __name__ == '__main__':
main()
使用上述数据的结果:
Name=A Run=true Idle=15
Name=B Run=true Idle=10
Name=D Run=true Idle=92
答案 1 :(得分:0)
差不多......如果......让我们走到最里面...... 此时,您需要提取值:
field_list = line.split(' ')
字段列表现在是三个字符串的列表,即空格分隔的字段。现在,抓住最后一个并分成等号:
idle_field = field_list[-1].split('=')
idle_field现在包含两个字符串:&#34; Idle&#34;和号码。最后:
if int(idle_field) >= 10:
print "\n", line
满足您的条件。
可以将所有处理折叠到if条件中,但我建议保持程序可读。 : - )
答案 2 :(得分:0)
您试图通过在字符串中搜索整数来比较整数。试试这个
public static void main(String[] args) {
// Create an arraylist of Capsule class' objects
ArrayList<Capsule> capsules = new ArrayList<>();
// Create any number of capsule objects in an unsorted manner
Capsule cap1 = new Capsule(1, 'a');
Capsule cap3 = new Capsule(3, 'c');
Capsule cap2 = new Capsule(2, 'b');
// Add them all to arraylist
capsules.add(cap1);
capsules.add(cap3);
capsules.add(cap2);
// Implement your sorting algorithm here...
// instead of sorting the numbers, sort the capsule objects
// For example you want to implement bubble sort...
for(int i = 0; i < capsules.size() - 1; i++) {
for(int j = 0; j < capsules.size() - i - 1; j++) {
if(capsules.get(d) > capsules.get(d + 1)) {
Capsule temp = capsules.get(d);
capsules.set(d, capsules.get(d + 1));
capsules.set(d + 1, temp);
}
}
}
// Finally print the results
for(int i = 0; i < capsules.size(); i++)
System.out.println("["+capsules.get(i).getNumber()+", "+capsules.get(i).getLetter()+"]");
}