【发布时间】:2021-08-04 07:17:28
【问题描述】:
我有test_final.txt,上面有一些简单的词,几句话。我想使用shuffle 方法来混合单词。最大的问题是,运行代码后,我的test_final.txt 变为空。第二个问题,不知道为什么Shuffle方法不行。
import random
import re
import sys
f = open("test_final.txt", "r")
print(f.read())
mama = r"([a-zA-Z]+) (\d+)"
listOfWords = re.findall(mama, 'f')
print("Result: ", listOfWords)
random.Random(4).shuffle(listOfWords)
print("Shuffled stuff: ", listOfWords)
finalString = ""
for cuvant in listOfWords:
finalString = finalString + cuvant + " "
finalString = finalString.strip()
print(finalString)
#SAve
with open("test_final.txt", "w", encoding = 'utf-8') as file:
file.write(finalString)
- 比如我有一些话变成了
test_final.txt:
my book is still here,输出应该是这样的
still book here is my.
- 运行代码后,
test_final.txt变为空。 (问题出在 save 方法上。但是,如果我在没有save的情况下进行测试,它不会像我需要的那样将这个词与 Shuffle Method 混合
【问题讨论】:
-
listOfWords = re.findall(mama, 'f')- 你能解释一下'f'是什么意思吗? -
您在第四行以读取模式打开同一个文件,并且从不关闭它。所以要么在阅读后致电
f.close(),要么使用with -
f来自f = open("test_final.txt", "r")(我尝试与文件建立连接) -
请edit 显示示例输入文件并说明您真正想要的结果。
-
我更新帖子
标签: python python-3.x python-requests