簡體   English   中英

在python中將單詞分隔成字母文件

[英]Separate words into alphabetical files in python

我正在使用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()方法返回網頁中的所有文本。 我不確定從這里去哪里。 有人可以幫忙嗎?

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]))

我認為應該工作(未經測試...)

首先打開文件,執行工作,然后關閉它們:

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM