Python用给定的形式写句子

2024-04-25 00:49:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份只有一句话的档案。我让用户选择“行”和“列”的数量。我想看看我能在这种表格里写多少遍这个句子而不分裂好的。现在我希望文本的形式如下: 输入: 行数=3 列=10 档案中的场景:猫有狗。 输出: 猫有*** 狗。猫** 他有狗。**

这个程序不能分割单词,也不能在它们不适合的地方放置星星。这是我做的代码的一部分,但我觉得我没有朝着好的方向走。你知道吗

我的问题: 1如何改进代码? 2如何让它既算得上汉字,又算得上文字? 三。此任务的一般提示。你知道吗

我的代码:

import sys
columns, rows, path = sys.argv[1:]
columns=int(columns)
rows=int(rows)
file=open(path,"r")
text=file.read()
list=list(text.split())
length=len(list)
for i in range(length):
    k=len(lista[i])
    if k<=columns:
        print(list[i], end=" ")
    else:
        print("*") 

Tags: columnspath代码text用户数量lensys
1条回答
网友
1楼 · 发布于 2024-04-25 00:49:30

这比我想象的要难。可能有一个更简单的解决方案,但您可以尝试以下方法:

list_of_words = text.split()
current_character_count_for_row = 0
current_string_for_row = ""
current_row = 1
how_many_times_has_sentence_been_written = 0

is_space_available = True
# Keep going until told to stop.
while is_space_available:

    for word in list_of_words:
        # If a word is too long for a row, then return false.
        if len(word) > columns:
            is_space_available = False
            break

        # Check if we can add word to row.
        if len(word) + current_character_count_for_row < columns:
            # If at start of row, then just add word if short enough.
            if current_character_count_for_row == 0:
                current_string_for_row = current_string_for_row + word
                current_character_count_for_row += len(word)
            # otherwise, add word with a space before it.
            else:
                current_string_for_row = current_string_for_row +" " + word
                current_character_count_for_row += len(word) + 1
        # Word doesn't fit into row.
        else:

            # Fill rest of current row with *'s.
            current_string_for_row = current_string_for_row + "*"*(columns - current_character_count_for_row)

            # Print it.
            print(current_string_for_row)

            # Break if on final row.
            if current_row == rows:
                is_space_available = False
                break
            # Otherwise start a new row with the word
            current_row +=1
            current_character_count_for_row = len(word)
            current_string_for_row = word
    if current_row > rows:
        is_space_available = False
        break

    # Have got to end of words. Increment the count, unless we've gone over the row count.
    if is_space_available:
        how_many_times_has_sentence_been_written +=1




print(how_many_times_has_sentence_been_written)

相关问题 更多 >