【Python程序设计】字符串的应用

Alex_Shen
2021-08-22 / 0 评论 / 0 点赞 / 72 阅读 / 5,831 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2022-04-06,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

1. 字符串推导式

我们之前学过列表推导式。例如,生成前 4 个奇数,我们可以写

[2 * num - 1 for num in range(1,5)] # 生成[1, 3, 5, 7]

仿照上面写法,使用推导式完成以下字符串操作:

  1. [‘apple’, ‘orange’, ‘pear’] -> [‘A’, ‘O’, ‘P’] # 第一个字母大写
  2. [‘apple’, ‘orange’, ‘pear’] -> [‘apple’, ‘pear’] # 是否包含字母’p’
  3. [“TA_parth”, “student_poohbear”, “TA_michael”, “TA_guido”, “student_
    htiek”] -> [“parth”, “michael”, “guido”] #是否以 TA_开头
  4. [‘apple’, ‘orange’, ‘pear’] -> [(‘apple’, 5), (‘orange’, 6), (‘pear’, 4)]
    #生成列表
  5. [‘apple’, ‘orange’, ‘pear’] -> {‘apple’: 5, ‘orange’: 6, ‘pear’: 4} #生成字典
list1 = ['apple', 'orange', 'pear']
print([i[0].upper() for i in list1])

list2 = ['apple', 'orange', 'pear']
print([i for i in list2 if i.count('p') > 0])

list3 = ["TA_parth",  "student_poohbear",
         "TA_michael",  "TA_guido",  "student_htiek"]
print([i[3:] for i in list3 if i.startswith('TA_')])

list4 = ['apple', 'orange', 'pear']
print([{i, len(i)} for i in list4])

list5 = ['apple', 'orange', 'pear']
print({i: len(i) for i in list5})

在这里插入图片描述

2. 特殊单词

有一种特殊的英文单词,它的相邻字母对之间的“距离”不断增加。如单词 subway,它的相邻字母对分别为 (s, u), (u, b), (b, w), (w, a), (a, y), 字母之间的距离依次为 2,19,21,22,24(如 a 是第 1 个字母,y 是第 25 个字母,a 和 y 的距离为 24)。编写函数is_special_word(word),word 为输入单词字符串,如为特殊单词,返回 True;否则返回 False。

import string

dic = {i: string.ascii_lowercase.find(i) + 1 for i in string.ascii_lowercase}

def is_special_word(word):
    for i in range(len(word)-2):
        if abs(dic[word[i+2]]-dic[word[i+1]]) < abs(dic[word[i+1]]-dic[word[i]]):
            return False
return True
word = str(input("请输入单词:"))
print(is_special_word(word))

在这里插入图片描述

3. Caesar 加密

Caesar 加密将文本中每个字符向前移动三个字母,即A->D,B->E,…,X->A,Y->B,Z->C如单词 PYTHON,将加密为 SBWKRQ。编写加密函数 encrypt_caesar(plaintext)和decrypt_caesar(ciphertext),每个函数都接受一个参数,表示将要加密或解密的字符串,然后返回加密或解密之后的字符串。

注:(1)只考虑大写字母;(2)非字母字符不需要通过加密或解密来修改。如encrypt_caesar(“F1RST
P0ST”)应该返回“I1UVW S0VW”;(3)encrypt_caesar(“”)应返回“”,即空字符串。

import string

def encrypt_caesar(plaintext):
    before = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    after = 'DEFGHIJKLMNOPQRSTUVWXYZABC'
    table = ''.maketrans(before, after)
return plaintext.translate(table)

def decrypt_caesar(ciphertext):
    after = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    before = 'DEFGHIJKLMNOPQRSTUVWXYZABC'
    table = ''.maketrans(before, after)
    return ciphertext.translate(table)

word1 = str(input("请输入加密单词:"))
print(encrypt_caesar(word1))
word1 = str(input("请输入解密单词:"))
print(decrypt_caesar(word1))

在这里插入图片描述

4. 杨辉三角

编写函数 print_yanghui_triangle(N),输出杨辉三角的前 N 行,要求使用 format 函数进行格式化输出

def print_yanghui_triangle(N):
    triangle = [['1'] for i in range(N)]
    for i in range(1, N):
        triangle[i].extend(str(int(triangle[i-1][j])+int(triangle[i-1][j+1]))
                           for j in range(len(triangle[i-1])-1))
        triangle[i].append('1')

    for i in range(len(triangle)):
        # print('{:^30}'.format(' '.join(triangle[i])))
        print(' '.join(triangle[i]).center(len(' '.join(triangle[N-1]))))

N = int(input('N:'))
print_yanghui_triangle(N)

Center方法:
在这里插入图片描述
Format方法:
在这里插入图片描述

5. 可读性等级

不同书的阅读群体不一样。例如,一本书中可能有许多很长的复杂单词;而较长的单词可能与较高的阅读水平有关。同样,较长的句子也可能与较高的阅读水平相关。研究者开发了许多可读性测试,给出了计算文本阅读水平的公式化过程。其中一个可读性测试是 Coleman Liau 指标:文本的 Coleman Liau 指标旨在划分理解文本所需的阅读水平等级。Coleman Liau 指标公式如下

index = 0.0588 * L - 0.296 * S - 15.8

其中,L 是文本中每 100 个单词的平均字母数,S 是文本中每 100 个单词的平均句子数。

考虑以下文本:

Congratulations! Today is your day. You’re off to Great Places! You’re
off and away!

该文本有 65 个字母,4 个句子,14 个单词。文本中每 100 个单词的平均字母数是L=65/14100=464.29;文本中每 100 个单词的平均句子数是 S=4/14100=28.57。代入 Coleman Liau 指标公式,并向最近的整数取整,我们得到可读性指数为 3级。

我们将编写一个函数 readability,输入参数为字符串,返回可读性等级。

实现要求:

(1) 若计算结果小于 1,输出“Before Grade 1”;
(2) 若计算结果大于或等于 16,输出“Grade 16+”;
(3) 除(1)和(2)外,输出“Grade X”,X 为相应等级。
(4) 字母包括大写字母和小写字母(不考虑数字和标点符号);
(5) 以空格分隔作为标准区分单词,如
It was a bright cold day in April, and the clocks were striking thirteen. Winston Smith, his chin nuzzled into his breast in an effort to escape the vile wind, slipped quickly through the glass doors of Victory Mansions, though not quickly enough to prevent a swirl of gritty dust from entering along with him.
55 words
(6) 句号(.)、感叹号(!)或问号(?)表示句子的结尾。如
Mr. and Mrs. Dursley, of number four Privet Drive, were proud to say that they were perfectly normal, thank you very much.
3 sentences
(7) 可读性等级的参考例子见 readability.txt。

import re

def readability(passage):
    word_num = len(passage.split())
sentence_num = len(re.split('[.?!]', passage))-1

    alpha_num = 0
    for i in range(len(passage)):
        if passage[i].isalpha():
            alpha_num += 1

    L = alpha_num/word_num*100
    S = sentence_num/word_num*100
return round(0.0588*L-0.296*S-15.8)

sentence_list = ["One fish. Two fish. Red fish. Blue fish.",
                 "Would you like them here or there? I would not like them here or there. I would not like them anywhere.",
                 "Congratulations! Today is your day. You're off to Great Places! You're off and away!",
                 "Harry Potter was a highly unusual boy in many ways. For one thing, he hated the summer holidays more than any other time of year. For another, he really wanted to do his homework, but was forced to do it in secret, in the dead of the night. And he also happened to be a wizard.",
                 "In my younger and more vulnerable years my father gave me some advice that I've been turning over in my mind ever since.",
                 "When he was nearly thirteen, my brother Jem got his arm badly broken at the elbow. When it healed, and Jem's fears of never being able to play football were assuaged, he was seldom self-conscious about his injury. His left arm was somewhat shorter than his right; when he stood or walked, the back of his hand was at right angles to his body, his thumb parallel to his thigh.",
                 "There are more things in Heaven and Earth, Horatio, than are dreamt of in your philosophy.",
                 "It was a bright cold day in April, and the clocks were striking thirteen. Winston Smith, his chin nuzzled into his breast in an effort to escape the vile wind, slipped quickly through the glass doors of Victory Mansions, though not quickly enough to prevent a swirl of gritty dust from entering along with him.",
                 "A large class of computational problems involve the determination of properties of graphs, digraphs, integers, arrays of integers, finite families of finite sets, boolean formulas and elements of other countable domains."]
for sentence in sentence_list:
    index = readability(sentence)
    if index < 1:
        print('Before Grade 1')
    elif index >= 16:
        print('Grade 16+')
    else:
        print('Grade', index)

在这里插入图片描述

0

评论区