Python Programming assignment 5 gives you a collection of poems

Design idea:

Use the dictionary to store each person's corresponding poem and poem name, and use the pilot library to build pictures.

Implementation scheme

First use The csv file stores the person's name according to Build an empty dictionary from the items in the csv file. Read into the whole Tang poetry txt file, find out the poem of each word in the person's name according to the regular expression, and form a list with its poem name and this poem at the same time. Then form these lists into a list. Use the random function to extract a sentence from the list of each word as a poem. Store it in the previous empty dictionary. So, in this dictionary Each item in the csv file corresponds to a key in the dictionary, and a key corresponds to a list. Four lists are stored, which correspond to the verse and poem name of "gift" and three words of person's name respectively.

Then use the pilot library to build the picture. Five pictures are prepared in advance from the evening as the background, and one of them is selected as the background of a card by using the random function. Use the resize of pilot to resize, and use pilot The ImageDraw library generates the corresponding text and finally saves it.

Key code description

Build dictionary section

f = csv.reader(open('name.csv'))    # Read csv file
names = []
for item in f:
    names.append(item[0])   # Add each item in the file to the list

f = open('tangshi.txt', 'r', encoding='utf-8')  # Read in txt file
lines = f.readlines()
f.close()

names_dict = {}
for name in names:
    name = 'Gift'+name    # Construction of poem title
    content = []
    which_poem = []
    for i in range(4):
        estring = name[i]+'[^,. ()!?<>: ;""]{6}[,. !?]'  # Constructing regular expressions for poems
        e1 = re.compile(estring)
        estring = '[[^]]*]'  # Constructing regular expressions for poem names
        e2 = re.compile(estring)
        poem_name = ""
        find_result = []
        # Find the result according to the regular expression and add it to the list
        for line in lines:
            line = line.replace(u'\u3000', u' ')
            if(e2.findall(line) != []):
                poem_name = line[line.find('['):line.rfind("\\")]
            if(e1.findall(line) != []):
                result = [poem_name, e1.findall(line)[0]]
                find_result.append(result)
        result = random.choice(find_result) # Selecting results by random function
        # Refactoring punctuation
        if i % 2 == 0:
            result[1] = result[1][0:7]+','
        else:
            temp = random.randint(0, 2)
            biaodian = ['. ', '?', '!']
            result[1] = result[1][0:7]+biaodian[temp]
        content.append(result)
    names_dict[name] = content  # Finally added to the dictionary

Build picture section

for name in names_dict:
    num=random.randint(1,5) # Use the random function to select the background image
    img = Image.open('background/'+str(num)+'.png')
    img=img.resize((800,1000))  # Use the resize function to resize the background picture
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype(font='JiangPanJiuShiYue-2.ttf', size=36)

    # Letterhead
    draw.text(xy=(100,150),text="dear",fill=(0,0,0),font=font)
    draw.text(xy=(208,150),text=name[1:],fill=(random.randint(0,255),random.randint(0,255),random.randint(0,255)),font=font)
    draw.text(xy=(300,150),text=": ",fill=(0,0,0),font=font)
    draw.text(xy=(172,200),text="I wrote a poem for you. I hope you like it:",fill=(0,0,0),font=font)

    # Part of the poem
    i=0
    for si in names_dict[name]:
        draw.text(xy=(172,250+i*50),text=si[1][0],fill=(random.randint(0,255),random.randint(0,255),random.randint(0,255)),font=font)
        draw.text(xy=(208, 250+i*50), text=si[1][1:], fill=(0, 0, 0), font=font)
        i=i+1
    
    # End of letter
    draw.text(xy=(172,500),text="Sincerely",fill=(0,0,0),font=font)
    draw.text(xy=(100,550),text="Salute!",fill=(0,0,0),font=font)
    draw.text(xy=(550,650),text="Guo Zeyu",fill=(0,0,0),font=font)
    draw.text(xy=(550,700),text="2021/6/17",fill=(0,0,0),font=font)

    # Remarks section
    font = ImageFont.truetype(font='MoRanXingKai-2.ttf', size=12)
    draw.text(xy=(100,600),text="remarks:",fill=(0,0,0),font=font)
    i=0
    for si in names_dict[name]:
        draw.text(xy=(136, 600+i*15), text=si[0], fill=(0, 0, 0), font=font)
        i=i+1

    # Save picture
    file_path="card/"+name+".png"
    img.save(file_path)

Effect display

experience

This assignment mainly focuses on the use of regular expressions and various containers we talked about in class. It is not very difficult. The most time-consuming part is the part that finally builds the greeting card. At the beginning, I chose to use markdown to build greeting cards and then convert them to pdf. The main difficulties encountered are the format of building markdown files (line feed, background, etc.) and finally converting md files into pdf files. The latter one has never been solved, so after spending a lot of time, we have to replace it with the way of using the pilot library to build pictures to complete this operation.

At the beginning, I really didn't expect that the conversion of md files into pdf files didn't improve, and I didn't expect that python would have so many problems writing md. So it takes a lot of time. This reminds us that before achieving the goal, we need to fully understand and judge the method. We can't do it blindly, which will only be laborious and thankless in the end.

This assignment has been uploaded to Github and Gitee. I hope you can click star before you go 😄.

GitHub

Gitee

Keywords: Python

Added by rocklv on Mon, 31 Jan 2022 23:57:34 +0200