Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

python - 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.

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.

lkhlknlkn nklnkjhn nbkjkjhkjhgjhgchghgchgd jhfhgdfgd jhjhgfkfdytd jjhfdtd. kjbkjbjhjhvbjh kbjhjhv jbjhgffdytdtrsr jhvhfgfgdsdrts hghfcdrt.

question from:https://stackoverflow.com/questions/65923680/i-have-some-data-in-a-file-format-i-want-to-know-what-is-the-first-string-in-ea

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One option is to use enumerate and specify a condition where the line index is >= 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:

with open("sample.txt") as data:
    my_lines = [line for line in data][2:]
for line in my_lines:
    print(line)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...