-4

How do you split a list by space? With the code below, it reads a file with 4 lines of 7 numbers separated by spaces. When it takes the file and then splits it, it splits it by number so if i print item[0], 5 will print instead of 50. here is the code

def main():
    filename = input("Enter the name of the file: ")
    infile = open(filename, "r")
    for i in range(4):
        data = infile.readline()
        print(data)
        item = data.split()
        print(data[0])

main()

the file looks like this

50 60 15 100 60 15 40 /n 100 145 20 150 145 20 45 /n 50 245 25 120 245 25 50 /n 100 360 30 180 360 30 55 /n

  • 2
    read the documentation of `.split()` [here](https://docs.python.org/3/library/stdtypes.html#str.split) – usernamenotfound Dec 05 '17 at 23:51
  • http://idownvotedbecau.se/noresearch/ You have the search terms, but didn't follow the posting guidelines. [on topic](http://stackoverflow.com/help/on-topic) and [how to ask](http://stackoverflow.com/help/how-to-ask) apply here. – Prune Dec 05 '17 at 23:57
  • Durr. `item[0]` is the first entry in the result list of the split. `data[0]`is the first character of the string you are splitting. – DisappointedByUnaccountableMod Dec 07 '17 at 11:25

3 Answers3

1

Split takes as argument the character you want to split your string with.

I invite you to read the documentation of methods you are using. :)

EDIT : By the way, readline returns a string, not a **list **. However, split does return a list.

IMCoins
  • 3,149
  • 1
  • 10
  • 25
1
import nltk

tokens = nltk.word_tokenize(TextInTheFile)

Try this once you have opened that file.

TextInTheFile is a variable

0

There's not a lot wrong with what you are doing, except that you are printing the wrong thing.

Instead of

print(data[0])

use

print(item[0])

data[0] is the first character of the string you read from file. You split this string into a variable called item so that's what you should print.