【问题标题】:Separate words into alphabetical files in python在python中将单词分成字母文件
【发布时间】:2013-12-04 18:21:06
【问题描述】:

我正在使用 Python 开发一个项目,并尝试将单词列表分成按字母顺序排列的文件。因此,任何以“a”或“A”开头的单词都会进入“A.html”文件。我能够创建文件并拥有以该字母开头的所有单词,但我需要递归地执行此操作,以便它将遍历所有字母并将它们放入不同的文件中。这是一些代码: 类 LetterIndexPage(object):

   def __init__(self, wordPage):
       self.alphaList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','Numbers','Special Characters']

   def createLetterPages(self):
       if not os.path.exists('A.html'):
           file('A.html', 'w')
       letterFileName = 'A.html'
       letterItemList = []
       for item in wordItems():
           if item[:1] == 'a' or item[:1] == 'A':
               letterItemList.append(item)
       letterItems = reduce(lambda letterItem1, letterItem2: letterItem1 + letterItem2, letterItemList)
       return letterItems

wordItems() 方法返回网页中的所有文本。我不知道从这里去哪里。有人可以帮忙吗?

【问题讨论】:

  • umm 递归可能不是完成此任务的最佳方式...
  • FWIW,您可以使用string.uppercase 而不是列出所有大写字符
  • from string import ascii_uppercase

标签: python file alphabetical


【解决方案1】:

先打开文件,完成工作,然后关闭它们:

from string import ascii_uppercase

output_files = {letter: open(letter + '.html', 'w') for letter in ascii_uppercase}
for word in list_of_words:
    output_files[word[0].upper()].write(word + '\n')

for of in output_files:
    of.close()

【讨论】:

    【解决方案2】:
    from itertools import groupby
    import requests
    page = requests.get('http://www.somepage.com/some.txt')
    all_words = page.text.split()
    groups = groupby(sorted(all_words),lambda x:x[0].lower())
    for g in groups:
       with open("%s.html"%g[0],"a") as f:
            f.write("\n".join(g[1]))
    

    我认为应该可以工作(无需测试...)

    【讨论】:

      猜你喜欢
      • 2023-02-25
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-10
      • 1970-01-01
      相关资源
      最近更新 更多