【问题标题】:Python Pig Latin convertor and line/word counterPython Pig 拉丁语转换器和行/字计数器
【发布时间】:2016-08-05 10:52:04
【问题描述】:

我必须创建一个 python 文件,提示用户输入文本文档的文件路径,然后将其转换为 pig Latin 并计算行/字数。

• 生成单个单词的猪拉丁版本的函数

• 将行数和字数打印到标准输出的函数

• 使用与原始文本文件相同的格式更正 pig Latin 输出

• 正确的行数和字数

我不明白为什么拉丁语会出错。我的老师说我需要另一个string.strip("\n"),因为它会使单词转换错误,但我不知道应该把它放在哪里。

我的线路计数器也坏了。它很重要,但它总是说 222 行

我怎样才能让它只计算单词的行数?

#Step 1: User enters text file.
#Step 2: Pig Latin function rewrites file and saves as .txt.
#Step 3: Tracks how many lines and words it rewrites.


vowels = ("A", "a", "E", "e", "I", "i", "O", "o", "U", "u")

# Functions

def pig_word(string):
    line = string.strip("\n")
    for word in string.split(" "):
        first_letter = word[0]
        if first_letter in vowels:
            return word + "way"     
        else:
            return word[1:] + first_letter + "ay"    

def pig_sentence(sentence):
    word_list = sentence.split(" ")
    convert = " "   
    for word in word_list:
        convert = convert + pig_word(word)    
        convert = convert + " "   
    return convert

def line_counter(s):
    line_count = 0
    for line in s:
        line_count += 1
    return line_count

def word_counter(line):
    word_count = 0
    list_of_words = line.split()
    word_count += len(list_of_words)
    return word_count




# File path conversion

text = raw_input("Enter the path of a text file: ")
file_path = open(text, "r")
out_file = open("pig_output.txt", "w")


s = file_path.read()
pig = pig_sentence(s)
out_file.write(pig+" ")
out_file.write("\n")


linecount = line_counter(s)
wordcount = word_counter(s)


file_path.close()
out_file.close()

# Results

print "\n\n\n\nTranslation finished and written to pig_output.txt"
print "A total of {} lines were translated successfully.".format(linecount)
print "A total of {} words were translated successfully.".format(wordcount)
print "\n\n\n\n"

【问题讨论】:

    标签: python file translation counter language-translation


    【解决方案1】:

    你的第一个问题在这里:

    def pig_word(string):
        line = string.strip("\n")  #!!!! line is NEVER USED !!!
        for word in string.split(" "): #you want *line*.split here
    

    第二个问题是由遍历字符串引起的,它遍历每个字符,而不是像文件那样遍历每一行:

    >>> for i in "abcd":
    ...     print(i)    
    
    a
    b
    c
    d
    

    所以在你的line_counter 中而不是这样做:

    for line in s:
        line_count += 1
    

    你只需要这样做:

    for line in s.split("\n"):
        line_count += 1
    

    【讨论】:

      【解决方案2】:
      1. 第一个你没有得到你想要的输出的原因是因为在你的pig_word(string)函数中,当你把return放在你的@987654323里面时,你返回了字符串中的第一个单词@ 环形。此外,您的老师正在谈论将所有行放入函数中,并通过str.split('\n') 遍历每一行。 \n 代表“换行符”。

      您可以尝试这样的方法来纠正它。

      def pig_sentence(string):
          lines = []
          for line in string.split('\n'):
              new_string = ""
              for word in line.split(" "):
                  first_letter = word[0]
                  if first_letter in vowels:
                      new_string += word + "way"
                  else:
                      new_string += word[1:] + first_letter + "ay"
                  lines.append(new_string)
          return lines
      

      所做的更改

      • 初始化了一个新列表lines,我们可以在整个循环中附加该列表。

      • 遍历传入字符串中的每一行。

      • 为每一行创建一个新字符串new_string

      • 使用您的代码,但不是 returning,而是将其添加到 new_string,然后将 new_string 附加到我们的新行列表 lines

      • 请注意,这消除了对两个函数的需求。另请注意,我将pig_word 重命名为pig_sentence


      1. second 错误在您的函数line_counter(s) 中。您正在迭代每个字符而不是每一行。在这里再次添加 str.split('\n') 以通过将字符串拆分为行列表然后遍历列表来获得所需的输出。

      这里是修改后的函数:

      def line_counter(s):
          line_count = 0
          for _ in s.split('\n'):
              line_count += 1
          return line_count
      

      (由于您的文件 i.o. 没有任何错误,因此我将在此处使用字符串文字进行测试。)


      测试

      paragraph = """\
      Hello world
      how are you
      pig latin\
      """
      
      lines = line_counter(paragraph)
      words = sum([word_counter(line) for line in paragraph.split('\n')])
      out = pig_sentence(paragraph)
      
      print(lines, words, out)
      

      输出是我们所期望的!

      3 7 ['elloHay', 'elloHayorldway', 'owhay', 'owhayareway', 'owhayarewayouyay', 'igpay', 'igpayatinlay']
      

      【讨论】:

      • 非常感谢!!计数器现在可以工作,但是当我添加 pig_sentence 部分来更改我的两个函数时,我收到一个 TypeError: cannot concatenate 'str' and 'list' objects。我该如何解决这个错误?
      • 你目前有哪些功能?
      【解决方案3】:

      您只删除空格,您需要删除所有标点符号以及行尾字符。替换

      split(" ")
      

      split()
      

      你的句子列表相当于

      sentence = 'Hello there.\nMy name is Roxy.\nHow are you?
      

      如果您在split(" ")split() 之后打印,您会看到差异并获得预期的结果。

      此外,您会得到不正确的结果,因为您会将there 翻译成heretay。您需要循环以使其显示为erethay

      即在添加“ay”之前将每个辅音移到末尾,以便新单词以元音开头。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-13
        • 2016-02-17
        • 1970-01-01
        • 1970-01-01
        • 2013-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多