with open("words_alpha.txt", 'r') as f:
your_result = [line.split(',') for line in f.read().splitlines()]
for i in your_result:
for word in i:
x = len(word)
print(word)
if x == 1:
with open("1.txt", "a") as myfile:
myfile.write(word)
if x == 2:
with open("2.txt", "a") as myfile:
myfile.write(word)
if x == 3:
with open("3.txt", "a") as myfile:
myfile.write(word)
if x == 4:
with open("4.txt", "a") as myfile:
myfile.write(word)
if x == 5:
with open("5.txt", "a") as myfile:
myfile.write(word)
if x == 6:
with open("6.txt", "a") as myfile:
myfile.write(word)
if x == 7:
with open("7.txt", "a") as myfile:
myfile.write(word)
if x == 8:
with open("8.txt", "a") as myfile:
myfile.write(word)
if x == 9:
with open("9.txt", "a") as myfile:
myfile.write(word)
if x == 10:
with open("10.txt", "a") as myfile:
myfile.write(word)
if x == 11:
with open("11.txt", "a") as myfile:
myfile.write(word)
if x == 12:
with open("12.txt", "a") as myfile:
myfile.write(word)r
代码正确地从单词列表中打印单词,但是当附加相同的变量时,它只将第一个字母添加到每个文件中。该代码逐行输出单词,但附加时仅显示为一堆字母。 alpha Words txt 文件是一个每行都有单词的单词列表。我想按字母数对单词进行排序
在
for word in i
中,您正在迭代每个单词的字符,您需要删除此循环。您还应该用通用解决方案替换所有 if
条件
for word in your_result:
x = len(word)
print(word)
with open(f"{x}.txt", "a") as myfile:
myfile.write(word)