为了账号安全,请及时绑定邮箱和手机立即绑定

Python-以给定格式编写句子

Python-以给定格式编写句子

qq_花开花谢_0 2021-09-14 15:04:41
我有一个包含一句话的文件。我让用户选择“行”和“列”的数量。我想检查一下我可以在这种表格中写多少次而不拆分单词。现在我希望文本的形式是这样的:输入:行= 3列= 10个文件来自文件:猫有狗。输出:猫有***狗。猫**有狗。**该程序无法拆分单词,并且无法在无法放置星星的地方进行拆分。这是我所做的代码的一部分,但我觉得我没有朝着好的方向发展。我的问题: 1. 如何改进我的代码?2. 如何让它既能算字又能算字?3. 此任务的一般提示。我的代码:import syscolumns, 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 回答

?
慕工程0101907

TA贡献1887条经验 获得超5个赞

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


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)



查看完整回答
反对 回复 2021-09-14
  • 1 回答
  • 0 关注
  • 198 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号