Python-以给定格式编写句子

时间:2018-12-11 09:58:32

标签: python

我有一个句子的文件。我让用户选择“行”和“列”的数量。我想检查我可以在这种表格中写多少次而不拆分单词,现在我想要这样的文本形式: 输入: 行数= 3 列= 10 文件中的内容:猫有狗。 输出:     猫有***     狗。猫**     有狗。**

该程序无法在单词和单词不能容纳的地方拆分单词。这是我所做的代码的一部分,但是我觉得我的方向不对。

我的问题: 1.如何改善我的代码? 2.如何使字符和单词同时计数? 3.此任务的一般提示。

我的代码:

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("*") 

1 个答案:

答案 0 :(得分:0)

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

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)