简体   繁体   中英

How to extract data from .txt file that is separated by varying space size?

I am trying to extract data (date and time) from a .txt file, raise it one second and then compare it with the next piece of data so I can see if date and time are continuous.

For example:

15  6 19  9 12 59.0000000  
... some other stuff...  
15  6 19  9 13  0.0000000

The problem is that the number of spaces between the digits varies (one space if the data on its right is two digits, two spaces if the data on its right is one digit).

How can I extract the dates, increment one second and then compare them with the next date in the text without having to check for every space variation?

You can use string.split() , this splits the string by varying spaces .

And example -

>>> s = "Hello  Bye          Test"
>>> s
'Hello  Bye          Test'
>>> s.split()
['Hello', 'Bye', 'Test']

The split method of the string class already splits at any contiguous whitespace. So just do your_string.split()

Adding to the answer by @Anand S Kumar, you could then use

" ".join(s.split())

(space between double-quotes can be replaced by character(s) of your choice) to combine the text into a continuous string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM