【问题标题】:Read a word from a file one character at a time then create a word from characters从文件中读取一个单词,一次一个字符,然后从字符创建一个单词
【发布时间】:2019-12-03 01:40:26
【问题描述】:

所以基本上我必须接受一个命令行参数,它是一个文件,并一次读取一个字符。然后我必须获取字符并将这些单词重新创建为一个变量,我可以使用该变量将其传递给稍后将使用的函数。我在尝试创建单词时遇到问题,我将字符添加到一个空变量然后打印出来,但它只是每次都在新行上打印字符而不是完整的单词

UPDATE:: 代码有效,但它基本上是打印一个句子我需要它来打印单词所以我尝试添加一个新行语句,但什么也没做


argc = len(sys.argv)

cmdlength = argc - 1

if cmdlength != 2:
    print ("Usage error, expected 2 args got " + str(cmdlength))
    exit()
else:
    word = ""
    with open(sys.argv[1],"r") as fh: 
        while True:
            ch=fh.read(1)
            if not ch:
                #print("End of file")
                break
            word += ch
        print(word, "\n")

【问题讨论】:

    标签: python command-line-arguments


    【解决方案1】:

    您将word 重置为word = "" + ch 中的最后一个字符,并在每个循环中打印。

    相反,只需在循环之前将其设置为空字符串一次,每次遇到空格时,在循环中附加到它,并在每个空格之后和退出之前打印一次:

    import sys
    
    argc = len(sys.argv)
    
    cmdlength = argc - 1
    
    if cmdlength != 2:
        print ("Usage error, expected 2 args got " + str(cmdlength))
        exit()
    else:
        word = ""  # Once before the loop
        with open(sys.argv[1],"r") as fh: 
            while True:
                ch=fh.read(1)
                if not ch:
                    print(word) # print the last word we were building before quitting
                    print("End of file")
                    break
                if ch == ' ':
                    print(word)  # We got a space, let's print the word
                    word = ''    # and reset it to the empty string
                else:
                    word += ch  # we append the last char
    

    【讨论】:

    • 感谢您的帮助,但是现在我收到无效的语法错误,行 word = += ch, 编辑:已修复
    • 该代码在技术上有效,但它不是创建单词而是创建一个句子,我需要它来创建要传递给函数的单词
    • 我的错,我更新了你的代码并留下了=,我把它编辑掉了。关于您的第二条评论:您应该更新您的问题并使其更清楚。我将通过假设每次遇到空格时都想在新行上打印一个单词来更新代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 1970-01-01
    • 2021-05-07
    • 2016-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多