4

通常の文章を含むテキストファイルがあります。実際、そのファイルを入力している間急いでいたので、文の最初の単語の最初の文字を大文字にしました (英語の文法に従って)。

しかし今は、各単語の最初の文字を大文字にしたほうがよいと思います。何かのようなもの:

この文の各単語は大文字で表記されています

上記の文で注意すべき点は、is ofisは大文字ではありませんが、実際には3文字以下の単語をエスケープしたいと考えています。

私は何をすべきか?

4

5 に答える 5

5
for line in text_file:
    print ' '.join(word.title() if len(word) > 3 else word for word in line.split())

編集:句読点のカウントを省略するにlenは、次の関数に置き換えます。

def letterlen(s):
    return sum(c.isalpha() for c in s)
于 2012-07-26T17:28:48.450 に答える
4

NLTKを見てください。

各単語をトークン化し、大文字にします。「if」「of」などの単語は「ストップワード」と呼ばれます。あなたの基準が長さだけである場合、スティーブンの答えはそうする良い方法です. ストップ ワードを調べたい場合は、SO: How to remove stop words using nltk or pythonに同様の質問があります。

于 2012-07-26T17:29:42.500 に答える
3

単語を分割し、3文字より長い単語のみを大文字にする必要があります。

words.txt

each word of this sentence is capitalized
some more words
an other line

-

import string


with open('words.txt') as file:
    # List to store the capitalised lines.
    lines = []
    for line in file:
        # Split words by spaces.
        words = line.split(' ')
        for i, word in enumerate(words):
            if len(word.strip(string.punctuation + string.whitespace)) > 3:
                # Capitalise and replace words longer than 3 (without punctuation).
                words[i] = word.capitalize()
        # Join the capitalised words with spaces.
        lines.append(' '.join(words))
    # Join the capitalised lines.
    capitalised = ''.join(lines)

# Optionally, write the capitalised words back to the file.
with open('words.txt', 'w') as file:
    file.write(capitalised)
于 2012-07-26T17:37:17.027 に答える
1

本当に必要なのは、ストップ ワードのリストと呼ばれるものです。このリストがない場合は、自分で作成して次のようにすることができます。

skipWords = set("of is".split())
punctuation = '.,<>{}][()\'"/\\?!@#$%^&*' # and any other punctuation that you want to strip out
answer = ""

with open('filepath') as f:
    for line in f:
        for word in line.split():
            for p in punctuation:
                # you end up losing the punctuation in the outpt. But this is easy to fix if you really care about it
                word = word.replace(p, '')  
            if word not in skipwords:
                answer += word.title() + " "
            else:
                answer += word + " "
    return answer # or you can write it to file continuously
于 2012-07-26T17:50:39.077 に答える
0

テキスト ファイルのすべての要素をリストに追加できます。

list = []
f.open('textdocument'.txt)
for elm in f (or text document, I\'m too tired):
   list.append(elm)

リスト内のすべての要素を取得したら、各要素の長さをチェックする for ループを実行し、3 より大きい場合は最初の要素を大文字で返します。

new_list = []
for items in list:
   if len(item) > 3:
      item.title()    (might wanna check if this works in this case)
      new_list.append(item)
   else:
   new_list.append(item)    #doesn't change words smaller than three words, just adds them to the new list

そして、それが機能するかどうかを確認しますか?

于 2012-07-26T17:31:55.200 に答える