简体   繁体   中英

Python - line.split()

Hi so I just started Python programming so be ready to see me alot around with alot of questions. First one, I'm making a small program that will go get informations from a .txt file I created in this format :

10-50-100 11-78-245 12-123-354 Etc ...

If the user wants to go get the line that start with the "10". How can I go get it and return ALL the informations (10, 50 AND 100) ? When I use line.split(), it only returns me the first entry of the line ...

This is my code :

levelChart = open("RunescapeLevelsChart.txt", "r")
actualLevel = raw_input("Level : ")
if actualLevel in open("RunescapeLevelsChart.txt").read() :
    actualLevelSplit = actualLevel.split()
    print actualLevelSplit
else :
    print("Failed.")
raw_input("End")

If I for example enter 10. I want the program to return me 10, 50 AND 100. But it only returns me 10. How do I correctly use the line.split() to make it returns all the values on the line ?

Thanks !

From reading your post, I assume that every set of 3 numbers are not always on the different lines. And you're looking for every set that starts with whatever the user is looking for (eg 10).

Walking through your code...

levelChart = open("RunescapeLevelsChart.txt", "r")
actualLevel = raw_input("Level : ")

So far so good.

if actualLevel in open("RunescapeLevelsChart.txt").read() :

At this point, actualLevel is your input ('10' for example)

open("RunescapeLevelsChart.txt").read() stores the entire text file in memory.

So you're searching for '10' from the entire file. Which from your example, will evaluate to "True"

    actualLevelSplit = actualLevel.split()
    print actualLevelSplit

split() splits your string by whitespace. So here, you're splitting "10" into ['10'] (a list)

else:
    print("Failed.")
raw_input("End")
  • raw_input will wait for user input before trying to continue, I'm assuming you're trying to 'pause' here. Which what you have should work.

Now having said that.. this should get you what you want..

levelChart = open("RunescapeLevelsChart.txt", "r")
actualLevel = raw_input("Level : ")

for line in levelchart: # Read the file line-by-line.
  number_sets = line.split()
  for set in number_sets:
    if set.startswith(actualLevel + '-'):
      print set 
      #>>> "10-50-100"
      # Now you can further split each number into individual numbers
      nums = set.split('-')
      print nums 
      #>>> ['10', '50', '100']

      # At this point, you can fetch the numbers from the list

levelChart.close() # Dont' forget to close the file object when you're done.

Hope this helps.

There are more problems than just this.

For example, if you enter 23, it will find this entry: 12-123-354

If you only want to find things that start with 10, then you want to do this differently. For example, if you want 78 not to find the second example, you definitely need to do something different.

You are opening the same file twice, among some other problems in your code. Here's a cleaned up version:

lines = []
with open("RunescapeLevelsChart.txt", "r") as the_file:
    for line in the_file:
       lines.append(line)

actualLevel = raw_input("Level : ")

for each_line in lines:
   if actualLevel in each_line:
       print each_line
   else:
       print "Didn't find it"

print "End"

The problem in your case is

you are doing actualLevel.split() , here actualLevel is 10

and actualLevel.split() will return 10 only

In [23]: actualLevel = '10'

In [24]: actualLevel.split()
Out[24]: ['10']

Here you should split the line containing the actualLevel from the file

you should do something like

In [28]: content = open("RunescapeLevelsChart.txt").read()

In [29]: y = [x for x in content.split(' ') if actualLevel in x]

In [30]: y
Out[30]: ['10-50-100']

In [31]: y[0].split('-')
Out[31]: ['10', '50', '100']

You'd probably be better off storing the whole list in a file:

f = open("RunescapeLevelsChart.txt", "r")
lines = f.readlines()
for i in lines:
    if i.startswith(actualLevel + '-'):  # so it's actually the first element
        print i  # this prints the line
        print i.split('-')  # use this is you want a list of the numbers
# rest of code (don't forget to close the file!)

Your code is returning the first element because you're trying to split actualLevel , not the line itself.

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