python英文题02

本文包含一系列Python编程练习,涉及从文件中读取整数并计算其倍数,找出最长单词,提取列表前两个元素,求正偶数和,筛选5的倍数,计算辅音数量,按序打印字典键值对,以及英语到毛利词翻译。这些练习涵盖了基础文件I/O和数据处理技巧。
摘要由CSDN通过智能技术生成

1.Write a program that prompts the user to enter an integer and a filename and prints the number of multiples of the given integer in the file. The file will be a plain text file and the numbers will be separated by whitespace. You can assume that the file only contains valid integers.

num=int(input('Enter an integer: '))
f_name=input('Enter a filename: ')
with open (f_name,'r') as txt:
    list1=txt.read().split()
    sum=0
    for k in list1:   #可以不用
        k=int(k)
        if k%num==0:
            sum=sum+1
    if sum>1:
        print(f"There are {sum} multiples of {num} in the '{f_name}' file.")
    else:
        print(f"There is {sum} multiple of {num} in the '{f_name}' file.")

2.Write a program that prompts the user to enter a filename.  The program reads all the words in the file then prints the longest word.  You can assume that the file is a plain text file without any punctuation marks and that the words are separated by whitespace. If there is more than one element with the longest length, (e.g. "concealing" and "everything"), the program returns the one that is highest alphabetically (e.g. "everything" > "concealing" so "everything" would be printed if the longest length was 10).

f_name=input('Enter filename: ')
with open (f_name,'r') as txt:
    str=txt.read()
    list_word=str.split()
    len_max=0
    list_out=[]
    for i in list_word:
        if len(i)>len_max:
            len_max=len(i)
    for j in list_word:
        if len(j)==len_max:
            list_out.append(j)
    list_out.sort()
    lth_out=len(list_out)
    word=list_out[lth_out-1]
    print(f'The longest word is "{word}"')

3.Write a function named get_first2(items) that takes a list of items and returns a list containing the first 2 elements of items. You may assume that items has at least 2 elements.

def get_first2(a):
    lst_first2=[]
    for i in range(0,2):
        lst_first2.append(a[i])
    return lst_first2

4.Write a function named get_sum_positive_even(numbers) that takes a list of integers as a parameter and returns the sum of all values in the list of integers which are both positive and even. Note: if there are no numbers in the list that are both positive and even, then your function should return 0.

def get_sum_positive_even(a):
    lst_up=[]
    addi=0
    for i in a:
        if i>=0:
            lst_up.append(i)
    for j in lst_up:
        if j%2==0:
            addi+=j
    return addi

5.Write a function named get_multiples_of_5(numbers) that takes a single integer list as a parameter and returns a new list containing all the values in the list that are multiples of 5. You may wish to use list comprehension to select out the multiples of 5 from the list. The program should return an empty list if the parameter is an empty list or there are no multiples of 5 in the list.

def get_multiples_of_5(a):
    lst_5=[]
    for i in a:
        if i%5==0:
            lst_5.append(i)
    return lst_5

6.Write a function named count_consonants(word) that takes a string as a parameter and returns the number of consonants in the string. 

Note that there are 21 consonant characters (B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Y and Z), but your code should be able to handle both upper and lower case characters in the given string. The program should return 0 if the parameter is an empty string or there are no consonant characters in the string.

def count_consonants(a):
    chek='aeiouAEIOU'
    addi=0
    for i in a:
        if i not in chek:
            addi+=1
    return addi

7.Write a function called print_keys_values_inorder(dictionary) which takes a dictionary as a parameter. The keys are integers and the corresponding values are lists of unique words. The function should print the keys and the corresponding lists of unique words in sorted alphabetical order. You can assume that the dictionary is not empty.

def print_keys_values_inorder(dict):
    turn_lst=sorted(dict.items(), key=lambda x:x[0] ,reverse=False)
    for j in turn_lst:
        str = ''
        lst_sort=[]
        for i in j[1]:
            lst_sort.append(i)

        lst_sort.sort()

        for h in lst_sort:
            str = str + h + ' '
        print(j[0], str)

8.Write a Python program that translates English words into Maori words. A list of word pairs are stored in a text file with the following format:

Prompt the user to enter the name of a text file and an English word. Your program should read the contents of the text file and build a dictionary data structure. The English words are the keys and the Maori words are the corresponding values. 

Next, your program should print either a translation of the English word with its corresponding Maori word if it is in the dictionary, or a phrase saying that the English word is not in the dictionary.

f_name=input('Enter the English to Maori dictionary filename: ')
aim_word=input('Enter an English word: ')
with open (f_name,'r') as txt:
    content=txt.read()
    lst_in=content.split()
    #print(lst_in)
    lst_fst=[]
    lst_sec=[]
    for i in lst_in:
        lst_half=i.split(sep=':')
        #print(lst_half)
        lst_fst.append(lst_half[0])
        lst_sec.append(lst_half[1])
        #print(lst_fst)
    if aim_word in lst_fst:
        loca=lst_fst.index(aim_word)
        print(f"'{aim_word}' is translated into '{lst_sec[loca]}'.")
    else:
        print('Sorry that word doesn\'t exist in Maori!')

9.Write a program which prompts the user to enter a sentence and creates a dictionary with keys which are integers and corresponding values which are lists of unique words (lowercase). The list of words corresponding to a key contains all the unique words from the text that have a length equal to the key value. The corresponding lists of unique words should be in sorted alphabetical order.  The program should then print the contents of the dictionary formatted as the examples below.

sentence=input('Enter a sentence: ')
low_all=[]
list_in=sentence.split()
for k in list_in:
    k=k.lower()
    low_all.append(k)
low_all.sort()

dict1={}
for i in low_all:
    list_val=[]
    lth=len(i)
    if lth not in dict1:
        dict1[lth]=list_val
        dict1.get(lth).append(i)
    else:
        if i not in dict1[lth]:
            dict1.get(lth).append(i)
list_keys=sorted(dict1.items(), key=lambda x:x[0] ,reverse=False)
#print(list_keys)
for j in list_keys:
    str=''
    for h in j[1]:
        str=str+h+' '
    print(j[0],str)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值