【问题标题】:Python - line.split()Python - line.split()
【发布时间】:2013-01-16 04:23:34
【问题描述】:

大家好,我刚开始 Python 编程,所以准备好迎接我的很多问题。 第一个,我正在制作一个小程序,它将从我以这种格式创建的 .txt 文件中获取信息:

10-50-100 11-78-245 12-123-354 等等……

如果用户想去获取以“10”开头的行。我怎样才能得到它并返回所有信息(10、50和100)? 当我使用 line.split() 时,它只返回该行的第一个条目...

这是我的代码:

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")

例如,如果我输入 10。我希望程序返回 10、50 和 100。但它只返回 10。如何正确使用 line.split() 使其返回行?

谢谢!

【问题讨论】:

    标签: python split


    【解决方案1】:

    通过阅读您的帖子,我假设每组 3 个数字并不总是在不同的行上。您正在寻找以用户正在寻找的任何内容开头的每个集合(例如 10)。

    浏览您的代码...

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

    到目前为止一切顺利。

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

    此时,actualLevel 是您的输入(例如“10”)

    open("RunescapeLevelsChart.txt").read() 将整个文本文件存储在内存中。

    因此,您正在从整个文件中搜索“10”。从你的例子中,将评估为“真”

        actualLevelSplit = actualLevel.split()
        print actualLevelSplit
    

    split() 用空格分割你的字符串。所以在这里,您将“10”拆分为 ['10'](一个列表)

    else:
        print("Failed.")
    raw_input("End")
    
    • raw_input 将在尝试继续之前等待用户输入,我假设您尝试在此处“暂停”。你所拥有的应该工作。

    话虽如此..这应该可以满足您的需求..

    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.
    

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      问题远不止这些。

      例如,如果你输入 23,它会找到这个条目:12-123-354

      如果您只想查找以 10 开头的内容,那么您希望以不同的方式执行此操作。例如,如果你想让78 不找到第二个例子,你肯定需要做一些不同的事情。

      【讨论】:

        【解决方案3】:

        您打开同一个文件两次,以及您的代码中的一些其他问题。这是一个清理后的版本:

        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"
        

        【讨论】:

        • 你真的想在每一行之后都打印“没找到”吗?
        【解决方案4】:

        你的问题是

        你在做actualLevel.split(),这里actualLevel10

        actualLevel.split() 将只返回10

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

        在这里你应该从文件中拆分包含actualLevel的行

        你应该做类似的事情

        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']
        

        【讨论】:

          【解决方案5】:

          您最好将整个列表存储在一个文件中:

          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!)
          

          您的代码正在返回第一个元素,因为您尝试拆分 actualLevel,而不是行本身。

          【讨论】:

          • 为什么是lines = f.read.split() 而不是lines = f.readlines()
          • @Mahi 哦,对了,我以为这些行是用空格隔开的,我很傻。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多