5

現在、テキストファイルを入力し、各単語を分離してリストに整理しようとしています。

私が抱えている現在の問題は、テキスト ファイルからカンマとピリオドを取り除くことです。

私のコードは以下の通りです:

#Process a '*.txt' file.
def Process():
    name = input("What is the name of the file you would like to read from? ")

    file = open( name , "r" )
    text = [word for line in file for word in line.lower().split()]
    word = word.replace(",", "")
    word = word.replace(".", "")

    print(text)

私が現在得ている出力は次のとおりです。

['this', 'is', 'the', 'first', 'line', 'of', 'the', 'file.', 'this', 'is', 'the', 'second', 'line.']

ご覧のとおり、「ファイル」と「行」の語尾にはピリオドが付いています。

私が読んでいるテキストファイルは次のとおりです。

これはファイルの最初の行です。

これが2行目です。

前もって感謝します。

4

3 に答える 3

8

これらの線は効果がありません

word = word.replace(",", "")
word = word.replace(".", "")

リストコンプを次のように変更するだけです。

[word.replace(",", "").replace(".", "") 
 for line in file for word in line.lower().split()]
于 2013-03-20T22:53:07.300 に答える
6

多分stripより適切ですreplace

def Process():
    name = input("What is the name of the file you would like to read from? ")

    file = open(name , "r")
    text = [word.strip(",.") for line in file for word in line.lower().split()]
    print(text)
>>>ヘルプ(str.strip)
method_descriptorに関するヘルプ:

ストリップ(...)
    S.strip([chars])->文字列またはUnicode

    先頭と末尾が付いた文字列Sのコピーを返します
    空白が削除されました。
    Noneではなくcharsが指定されている場合は、代わりにchars内の文字を削除してください。
    charsがユニコードの場合、Sはストリッピング前にユニコードに変換されます
于 2013-03-20T22:53:47.863 に答える
0

これを試して:

 chars = [',', '.']

 word.translate(None, ''.join(chars))

Python3 の場合

 chars = [',', '.']
 word.translate({ord(k): None for k in chars})
于 2013-03-20T22:59:08.760 に答える