【问题标题】:Get only one word from line只取一行中的一个单词
【发布时间】:2017-03-19 12:07:54
【问题描述】:

如何从文件中的一行中只取出一个单词并将其保存在某个字符串变量中? 例如,我的文件有“this, line, is, super”行,我只想在变量 word 中保存第一个单词(“this”)。我试图逐个字符地阅读它,直到我打开“”,但是当我检查它时,我收到一个错误“'int'类型的参数不可迭代”。我该怎么做?

line = file.readline() # reading "this, line, is, super"
    if "," in len(line): # checking, if it contains ','
        for i in line:
            if "," not in line[i]: # while character is not ',' -> this is where I get error
                word += line[i] # add it to my string

【问题讨论】:

    标签: string python-2.7 file


    【解决方案1】:

    你可以这样做,使用split():

    line = file.readline()
    if "," in line:
        split_line = line.split(",")
        first_word = split_line[0]
        print(first_word)
    

    split() 将创建一个列表,其中每个元素在您的情况下是一个单词。不包含逗号。

    【讨论】:

    • 谢谢。 :) 您的解决方案非常简洁,将来我可能会使用您的想法。如果我有能力选择两个最佳答案,我肯定也会选择你的。但我需要选择一个,在这种情况下,我更看重好的解释而不是优雅的方法。
    【解决方案2】:

    乍一看,您走在了正确的轨道上,但是如果您始终考虑将哪种数据类型存储在哪里,您可以破译一些错误的事情。例如,您的条件 'if "," in len(line)' 没有意义,因为它转换为 'if "," in 21'。其次,您遍历行中的每个字符,但您对 i 的值不是您想的那样。您希望在 for 循环中的该点处的字符索引,以检查是否存在“,”,但 line[i] 不像 line[0],正如您想象的那样,它实际上是 line['t ']。很容易假设 i 始终是字符串中的整数或索引,但您想要的是一个整数值范围,等于行的长度,以便迭代,并在每个索引处找到关联的字符。我已重新格式化您的代码以按照您的预期工作,返回 word = "this",并考虑到这些说明。我希望你能找到这个指导性(有更短的方法和内置的方法可以做到这一点,但理解索引在编程中至关重要)。假设 line 是字符串“this, line, is, super”:

    if "," in line: # checking that the string, not the number 21, has a comma
        for i in range(0, len(line)): # for each character in the range 0 -> 21
            if line[i] != ",": # e.g. if line[0] does not equal comma
                word += line[i] # add character to your string
            else:
                break # break out of loop when encounter first comma, thus storing only first word
    

    【讨论】:

    • 感谢您解释我的错误。 :) 并且非常感谢您根据我的想法调整您的解决方案。
    猜你喜欢
    • 2011-04-14
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多