通过函数创建句子而不使用包

时间:2017-10-21 15:33:54

标签: python list sentence

我正在编写一个查看列表的程序,并将这些单词组合成句子,但每当我运行它时,我得到了[]并且我不是100%肯定为什么。这是我在文件中读取的代码,并创建了句子和列表的附加片段。

def import_file(text_file):
    wordcounts = []
    with open(text_file, encoding = "utf-8") as f:
        pride_text = f.read()
        sentences = pride_text.split(" ")
        return sentences





def create_sentance(sentance):
    sentence_list=[]
    my_sentence=""
    for character in sentance:
        if character=='.' or character=='?' or character=='!':
            sentence_list.append(my_sentence) 
            my_sentence=""
        else:
            my_sentence=my_sentence + character
        return sentence_list

Preview of List 调用我的功能

pride=import_file("pride.txt")
pride=remove_abbreviations_and_punctuation(pride)
pride=create_sentance(pride)
print(pride)

2 个答案:

答案 0 :(得分:0)

您的return sentence_list缩进了一个比它应该更远的地方。在for的第一次迭代之后,如果else条件执行而不是if,那么您的函数将返回sentence_list,该[ ]已初始化为sentence。无论哪种方式,如果for长度为20个字符,则return只会在def create_sentance(sentance): sentence_list=[] my_sentence="" for character in sentance: if character=='.' or character=='?' or character=='!': sentence_list.append(my_sentence) my_sentence="" else: # do you not want this in 'sentence_list'? my_sentence=my_sentence + character return sentence_list 来电的位置运行一次。

进行以下更改:

from tkinter import *

root=Tk()

grid= Frame(root)
grid.pack()

img0=PhotoImage(file="0.png")
img1=PhotoImage(file="1.png")
img2=PhotoImage(file="2.png")

fill = 1

class button:

    def __init__(self, x, y):

        self.type=0

        self.but=Button(grid,command=self.change, image=img0, borderwidth=0)
        self.but.grid(row=y, column=x)

    def change(self):

        if self.type==fill:
            self.but.config(image=img0)
            self.type=0
        else:
            self.but.config(image=eval("img"+str(fill)))
            self.type=fill

def create(x,y):

    grid_buttons = []

    for Y in range(y):
        grid_buttons.append([])
        for X in range(x):
            grid_buttons[Y].append(button(X, Y))

create(15,15)

root.mainloop()

答案 1 :(得分:0)

函数返回空列表的原因是因为返回在for循环中。另外,“character”实际上是一个单词,因为列表中的每个元素都是一个单词。该计划有效:

def create_sentance(sentance):
    sentence_list=[]
    my_sentence=""
    for character in sentance:
        print character
        if '.' in character or '?' in character or '!' in character:
            sentence_list.append(my_sentence + ' ' + character)
            my_sentence=""
        else:
            my_sentence=my_sentence + ' ' + character
    return sentence_list
create_sentance(['I','will','go','to','the','park.','Ok?'])

你需要使用“in”而不是==因为每个字符都是一个单词。尝试打印“字符”以查看此内容。上述程序可以运行并返回结果

[' I will go to the park.', 'Ok?']

这是你想要的。