通常の文章を含むテキストファイルがあります。実際、そのファイルを入力している間急いでいたので、文の最初の単語の最初の文字を大文字にしました (英語の文法に従って)。
しかし今は、各単語の最初の文字を大文字にしたほうがよいと思います。何かのようなもの:
この文の各単語は大文字で表記されています
上記の文で注意すべき点は、is ofとisは大文字ではありませんが、実際には3文字以下の単語をエスケープしたいと考えています。
私は何をすべきか?
通常の文章を含むテキストファイルがあります。実際、そのファイルを入力している間急いでいたので、文の最初の単語の最初の文字を大文字にしました (英語の文法に従って)。
しかし今は、各単語の最初の文字を大文字にしたほうがよいと思います。何かのようなもの:
この文の各単語は大文字で表記されています
上記の文で注意すべき点は、is ofとisは大文字ではありませんが、実際には3文字以下の単語をエスケープしたいと考えています。
私は何をすべきか?
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)
NLTKを見てください。
各単語をトークン化し、大文字にします。「if」「of」などの単語は「ストップワード」と呼ばれます。あなたの基準が長さだけである場合、スティーブンの答えはそうする良い方法です. ストップ ワードを調べたい場合は、SO: How to remove stop words using nltk or pythonに同様の質問があります。
単語を分割し、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)
本当に必要なのは、ストップ ワードのリストと呼ばれるものです。このリストがない場合は、自分で作成して次のようにすることができます。
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
テキスト ファイルのすべての要素をリストに追加できます。
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
そして、それが機能するかどうかを確認しますか?