Python - line.split()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14351356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - line.split()
提问by Aura
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 :
嗨,我刚开始 Python 编程,所以准备好带着很多问题来见我。第一个,我正在制作一个小程序,它将从我以这种格式创建的 .txt 文件中获取信息:
10-50-100 11-78-245 12-123-354 Etc ...
10-50-100 11-78-245 12-123-354 等...
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 ...
如果用户想要获取以“10”开头的行。我怎样才能得到它并返回所有信息(10、50 和 100)?当我使用 line.split() 时,它只返回我该行的第一个条目......
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 ?
例如,如果我输入 10。我希望程序返回我 10、50 和 100。但它只返回我 10。我如何正确使用 line.split() 使其返回该行上的所有值?
Thanks !
谢谢 !
采纳答案by jhuynh
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 (e.g. 10).
通过阅读您的帖子,我假设每组 3 个数字并不总是在不同的行上。并且您正在寻找以用户正在寻找的任何内容开头的每个集合(例如 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)
此时, actualLevel 是您的输入(例如“10”)
open("RunescapeLevelsChart.txt").read() stores the entire text file in memory.
open("RunescapeLevelsChart.txt").read() 将整个文本文件存储在内存中。
So you're searching for '10' from the entire file. Which from your example, will evaluate to "True"
因此,您正在从整个文件中搜索“10”。从您的示例中,哪个将评估为“真”
actualLevelSplit = actualLevel.split()
print actualLevelSplit
split() splits your string by whitespace. So here, you're splitting "10" into ['10'] (a list)
split() 用空格分割你的字符串。所以在这里,您将“10”拆分为 ['10'](一个列表)
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.
- raw_input 将在尝试继续之前等待用户输入,我假设您在此处尝试“暂停”。你所拥有的应该工作。
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.
希望这可以帮助。
回答by jgritty
There are more problems than just this.
问题还不止这些。
For example, if you enter 23, it will find this entry: 12-123-354
例如,如果你输入 23,它会找到这个条目: 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 78not to find the second example, you definitely need to do something different.
如果您只想查找以 10 开头的内容,那么您希望以不同的方式执行此操作。例如,如果您不想78找到第二个示例,您肯定需要做一些不同的事情。
回答by Burhan Khalid
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"
回答by avasal
The problem in your case is
你的问题是
you are doing actualLevel.split(), here actualLevelis 10
你在做什么actualLevel.split(),这actualLevel是10
and actualLevel.split()will return 10only
并且actualLevel.split()将返回10唯一
In [23]: actualLevel = '10'
In [24]: actualLevel.split()
Out[24]: ['10']
Here you should split the line containing the actualLevel from the file
在这里,您应该从文件中拆分包含 actualLevel 的行
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']
回答by Volatility
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.
您的代码正在返回第一个元素,因为您正在尝试 split actualLevel,而不是行本身。

