注: 提案を反映するために元のコードが変更されました。私のような初心者が参照できるように、元の投稿をほとんどそのままにしておきます。
これらの値の 0 から 4 つすべてを含むことができる csv ファイルがあります。
COLOUR,Code1,Code2
Red,1,A
White,3,D
Blue,1,C
Orange,2,D
次の内容を含むテスト ファイル (test_test.txt) があります。
"Colours have come to symbolize many things. "
私が苦労しているのは、値を置き換える方法がわからないことです。カラー ファイルを検索し、値が見つかった場合は、別の値に置き換えます。
"Red is the colour of blood, rubies, and strawberries." replaces Red
"WhitePages is the world's largest and most trusted source for business." replaces White
"The term blue moon is used colloquially to mean a rare event." replaces Blue
"Orange you glad I have no more colours?" replaces Orange
2 つの形式 (段落とリスト) でテキスト ファイルに書き込みたい:
Red is the colour of blood, rubies, and strawberries, WhitePages is the world's largest and most trusted source for business, The term "blue moon" is used colloquially to mean a rare event, and Orange you glad I have no more colours?
これをテキストドキュメントの中央に配置できるようにしたいと思います:
Red is the colour of blood, rubies, and strawberries
WhitePages is the world's largest and most trusted source for business
The term "blue moon" is used colloquially to mean a rare event
Orange you glad I have no more colours?
これは、提案が組み込まれた改訂されたコードです。最後の4つの文を中央に配置する方法について何か考えはありますか?
import csv
with open('C:/Test/test_text.txt', 'a') as f:
with open('C:/Test/colour.csv', 'rb') as test:
colour_dict = {
'Red': "Red is the colour of blood, rubies, and strawberries",
'White': "WhitePages is the world's largest and most trusted source for business",
'Blue': "The term blue moon is used colloquially to mean a rare event",
'Orange': "Orange you glad I have no more colours?"
}
reader = csv.DictReader(test)
colour_list = tuple([colour_dict[row["COLOUR"]] for row in reader])
# Wtite out comma separated list.
if len(colour_list) == 0:
colourGroup = exit
elif len(colour_list) == 1:
colourGroup = '%s' % colour_list #
elif len(colour_list) == 2:
colourGroup = '%s and %s' % colour_list
else:
colourGroup = ('%s, ' * (len(colour_list)-1) + 'and %s') % tuple(colour_list)
f.write(colourGroup)
# Write out list as separate lines.
f.write ('\n\ncolour can influence our emotions, our actions and how we respond to various people, things and ideas. Much has been studied and written about colour and its impact on our daily lives.\n\nMany people believe that colours are powers, and that bright colours are especially powerful. Here are some of the meanings of colours and the energies contained in their corresponding stones.')
f.write('\n\n' + ('\n'.join(colour_list)))
ありとあらゆる助けが大歓迎です。