[英]I have some data in a file format. I want to know what is the first string in each line and count how many times they are repeated
24
Lattice = " 4.86063327 0.0 0.0 0.0 5.88550146 0.0 0.0 0.0 9.91419763 "
Fe 2.191577 4.414126 7.674144
Fe 0.238740 4.414126 2.717045
Fe 2.669056 1.471375 2.240053
Fe 4.621894 1.471375 7.197152
P 4.381224 4.414126 5.887209
P 2.909726 4.414126 0.930110
P 0.479409 1.471375 4.026988
P 1.950908 1.471375 8.984087
O 1.026405 4.414126 6.149975
O 1.403911 4.414126 1.192876
O 3.834228 1.471375 3.764223
O 3.456722 1.471375 8.721321
O 3.174416 4.414126 9.346927
O 4.116534 4.414126 4.389828
O 1.686217 1.471375 0.567271
O 0.744100 1.471375 5.524369
O 3.659022 5.613562 6.613841
O 3.631928 3.214690 1.656742
O 1.201612 2.670811 3.300357
O 1.228705 0.271940 8.257456
O 1.201612 0.271940 3.300357
O 1.228705 2.670811 8.257456
O 3.659022 3.214690 6.613841
O 3.631928 5.613562 1.656742
I am trying to write a code in Python. However, I am not sure how to make a loop from line 3 to the end.我正在尝试在 Python 中编写代码。但是,我不确定如何从第 3 行到最后进行循环。
I am trying with a code like this我正在尝试使用这样的代码
with open("Structure") as f:
lines_after_2 = f.readlines()[2:]
for i in range((len(lines_after_2))):
symbol=lines_after_2[i].split()[0]
print(symbol)
if symbol='Fe':
count_Fe+=1
elif symbol=='P':
count_P+=1
elif symbol=='O':
count_O+=1
print(count_Fe)
print(count_P)
print(count_O)
But it says NameError: name 'count_Fe+=1' is not defined.但它说 NameError: name 'count_Fe+=1' is not defined。
lkhlknlkn nklnkjhn nbkjkjhkjhgjhgchghgchgd jhfhgdfgd jhjhgfkfdytd jjhfdtd. lkhlknlkn nklnkjhn nbkjkjhkjhgjhgchghgchgd jhfhgdfgd jhjhgfkfdytd jjhfdtd。 kjbkjbjhjhvbjh kbjhjhv jbjhgffdytdtrsr jhvhfgfgdsdrts hghfcdrt. kjbkjbjhjhvbjh kbjhjhv jbjhgffdytdtrsr jhvhfgfgdsdrts hghfcdrt。
One option is to use enumerate and specify a condition where the line index is >= 2:一种选择是使用枚举并指定行索引 >= 2 的条件:
with open("sample.txt") as data:
for idx, line in enumerate(data):
if idx >= 2:
print(line)
Another option is to consume the TextIOWrapper with a list comprehension and then slice the list:另一种选择是使用具有列表理解的 TextIOWrapper,然后对列表进行切片:
with open("sample.txt") as data:
my_lines = [line for line in data][2:]
for line in my_lines:
print(line)
In a file like this you can just use the count method for strings:在这样的文件中,您可以只对字符串使用 count 方法:
arq = open("Structure")
string = arq.read()
arq.close()
count_Fe = string.count('Fe')
Just take care, if there is something like 'Ferr' it will count the 'Fe'.请注意,如果有类似“Ferr”的内容,它将计算“Fe”。 But in a type of data like your exemple, it should work但是在像你的例子这样的数据类型中,它应该有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.