Python|从文本文件中打乱单词
给定文本文件中的一些数据,任务是将文本打乱并输出到单独的文本文件中。因此,我们需要编写一个Python程序来读取一个文本文件,打乱文件中的单词并将输出写入一个新的文本文件。
应遵守的规则:
- 小于或等于 3 个字符的单词不需要打乱。
- 不要打乱第一个和最后一个字符,所以加扰可以变成Srbmnacilg或Srbmnailcg或Snmbracilg ,即除了第一个和最后一个字符之外的字母可以按任何顺序加扰。
- 单词末尾的标点符号保持原样,即“Surprising,”可以变成“Spsirnirug,”但不是“Spsirn, irug”。
- 支持以下标点符号 - 逗号问号、句号、分号、感叹号。
- 对文件执行此操作并维护行序列。
在执行程序时,它应该提示用户输入输入文件名并生成带有乱码的输出文件。输出文件应通过在输入文件名后附加单词“Scrambled”来命名。
例子:
Input : MyFile.txt ->
Scrambling words is very
interesting. Because even
if they are scrambled, it
doesn't impact our
reading. Because we don't
read letter by letter, we
read the word as a whole.
Output : MyFileScrambled.txt ->
Srbmnacilg words is very
itrensientg. Bscauee even
if tehy are srelabcmd, it
dosn'et ipcmat our
raidneg. Bacusee we dn'ot
raed lteetr by letetr, we
raed the word as a wolhe.
下面是实现:
Python3
import random
punct = (".", ";", "!", "?", ",")
count = 0
new_word = ""
inputfile = input("Enter input file name:")
with open(inputfile, 'r') as fin:
for line in fin.readlines(): # Read line by line in txt file
for word in line.split(): # Read word by word in each line
if len(word) > 3: # If word length >3
'''If word ends with punctuation
Remove firstletter, lastletter and punctuation
Shuffle the words
Add the removed letters (first letter)
Add the removed letters (last letter)
Add the removed letters (punctuation mark)'''
if word.endswith(punct):
word1 = word[1:-2]
word1 = random.sample(word1, len(word1))
word1.insert(0, word[0])
word1.append(word[-2])
word1.append(word[-1])
'''If there is no punctuation mark
Remove first letter and last letter
Shuffle the word
Add the removed letters (first letter)
Add the removed letters (last letter)
Append the word and " " to the previous words'''
else:
word1 = word[1:-1]
word1 = random.sample(word1, len(word1))
word1.insert(0, word[0])
word1.append(word[-1])
new_word = new_word + ''.join(word1) + " "
'''If word length <3
just append the word and " " to the previous words'''
else:
new_word = new_word + word + " "
# "Append to Scrambled.txt"
with open((inputfile[:-4] + "Scrambled.txt"), 'a+') as fout:
fout.write(new_word + "\n")
new_word = ""
输出:
Smcinrablg wodrs very Bauscee eevn tehy dnoes't
icpamt Bcuesae d'not read lteter raed wrod whole.