0

I have a txt file that read line by line and the text file has some data as below. I am trying to extract the numbers so that I can process them as in array of something like that. The space in between dates and the start of the numbers are 'tabs" and the numbers have normal spaces.

04/10/2000 02 75 30 54 86
04/16/2000 63 63 48 32 12
04/15/2000 36 47 68 09 40
04/14/2000 06 27 31 36 43
04/13/2000 03 08 41 60 87

Here is the code I wrote:

    for line in handle:
       line = line.rstrip()
       numberlist.append(line.split('\t'))

   numbers=list()   
   numberlist=list()
   for x in numberlist:
       numbers.append(x[1]) 

   print(numbers[:2]) # just to see sample output 

Could someone help me to figure out? I checked some python tutorial even but the more I think about the issue, the more tricky and detailed it seems to me. (please note that this is not a homework)

Thanks

user156427
  • 15
  • 3

1 Answers1

1

You can split on a tab \t to get 2 parts. Then split the second part on a space to get all the numbers.

strings = [
    "04/10/2000 02 75 30 54 86",
    "04/16/2000 63 63 48 32 12",
    "04/15/2000 36 47 68 09 40",
    "04/14/2000 06 27 31 36 43",
    "04/13/2000 03 08 41 60 87"
]

numbers = list()
numberlist = list()

for s in strings:
    lst = s.rstrip().split("\t")
    if len(lst) > 1:
        lst = lst[1].split(" ")
        numberlist.append(lst)
        for n in lst:
            numbers.append(n)

print(numbers)
print(numberlist)

Output

['02', '75', '30', '54', '86', '63', '63', '48', '32', '12', '36', '47', '68', '09', '40', '06', '27', '31', '36', '43', '03', '08', '41', '60', '87']
[['02', '75', '30', '54', '86'], ['63', '63', '48', '32', '12'], ['36', '47', '68', '09', '40'], ['06', '27', '31', '36', '43'], ['03', '08', '41', '60', '87']]

Python demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • I got this trace error Traceback (most recent call last): File "", line 7, in IndexError: list index out of range – user156427 Apr 19 '21 at 19:07
  • @user156427 I have added a check to verify that the list has at least 2 items. – The fourth bird Apr 19 '21 at 19:11
  • Yes I am sure. Like I said I am reading this from a file as I show in my code. and I use your sample code on online python ide as the way it is and I got that error. – user156427 Apr 19 '21 at 19:12
  • @user156427 I have updated the code. Does that work out? – The fourth bird Apr 19 '21 at 19:12
  • OK it is because I copy and pasted from this page and tabs are acting like spaces. By the way how would I get rid of those "02" to 2. they are still strings right? So for each element using int() function on them would work. Am I right? – user156427 Apr 19 '21 at 19:14
  • @user156427 You could use for example https://ideone.com/bRPw8b – The fourth bird Apr 19 '21 at 19:17