【问题标题】:Removing \n from myFile从 myFile 中删除 \n
【发布时间】:2014-12-12 17:20:52
【问题描述】:

我正在尝试创建一个列表字典,其中键是字谜,值(列表)包含该字谜中所有可能的单词。

所以我的 dict 应该包含这样的内容

{'aaelnprt': ['parental', 'paternal', 'prenatal'], ailrv': ['rival']} 

可能的单词在 .txt 文件中。每个单词都用换行符分隔。示例

Sad
Dad
Fruit
Pizza

当我尝试对其进行编码时,这会导致问题。

with open ("word_list.txt") as myFile:
    for word in myFile:
        if word[0] == "v": ##Interested in only word starting with "v"
            word_sorted =  ''.join(sorted(word)) ##Get the anagram
            for keys in list(dictonary.keys()):
                if keys == word_sorted: ##Heres the problem, it doesn't get inside here as theres extra characters in <word_sorted> possible "\n" due to the linebreak of myfi
                    print(word_sorted)
                    dictonary[word_sorted].append(word)

【问题讨论】:

    标签: python anagram


    【解决方案1】:

    如果“word_list.txt”中的每个单词后跟'\n',那么你可以使用切片来去掉单词的最后一个字符。

    word_sorted = ''.join(sorted(word[:-1])) 
    

    但如果“word_list.txt”中的最后一个单词不是后跟'\n',那么你应该使用rstrip()

    word_sorted = ''.join(sorted(word.rstrip())) 
    

    slice 方法的效率稍高一些,但对于这个应用程序,我怀疑你会注意到其中的区别,所以你最好还是谨慎行事并使用rstrip()

    【讨论】:

      【解决方案2】:

      使用rstrip(),它会删除\n 字符。

      ...
      ...
      keys == word_sorted.rstrip()
      ...
      

      【讨论】:

      • 问:如果 word_sorted 有换行符,不应该只保留在字典的键值中。对不起,如果这是一个菜鸟问题,但换行符为什么要特别?
      【解决方案3】:

      您应该尝试在代码中使用 .rstrip() 函数,它会删除“\n”

      你可以在这里查看.rstrip()

      【讨论】:

        【解决方案4】:

        strip 仅删除字符串开头或结尾的字符。

        • 使用 rstrip() 删除 \n 字符

        您也可以使用替换语法,将换行符替换为其他内容。

        str2 = str.replace("\n", "")

        【讨论】:

          【解决方案5】:

          所以,我在这里看到了一些问题,如何进入字典,我没有看到任何作业?很明显,你只给我们提供了一个 sn-p,所以可能是在别处。

          当您可以使用 in 时,您还使用了循环(它更有效,确实如此)。

          with open ("word_list.txt") as myFile:
              for word in myFile:
                  if word[0] == "v": ##Interested in only word starting with "v"
                      word_sorted = ''.join(sorted(word.rstrip())) ##Get the anagram
                      if word_sorted in dictionary:
                          print(word_sorted)
                          dictionary[word_sorted].append(word)
                      else:
                          # The case where we don't find an anagram in our dict
                          dictionary[word_sorted] = [word,]
          

          【讨论】:

            猜你喜欢
            • 2012-04-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-08-16
            • 2018-05-03
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多