從文件內容讀取和執行操作

喬納森

所以我正在嘗試做這個實驗,從 .txt 文件中為您提供大量信息。每行包含一些字母和數字,我應該編寫代碼來回答文本每行的 5 個問題:使用小寫字母打印 5 個字母序列,打印 5 個字母序列是否包含任何元音,打印球體的體積具有第一個數字的半徑,打印剩餘的3個數字是否可以組成三角形,並打印最後3個數字的平均值。

以下是 Lab5_Data.txt 的 3 行:

WLTQS 13 64 23 99

ZNVZE 82 06 53 82

TMIWB 69 93 68 65

這是這 3 行的預期輸出:

小寫的字符串是wltqs

WLTQS 不包含任何元音

半徑為13的球體的體積是9202.7720799157

64、23、99不能構成三角形。

64、23、99的平均值是62.0

小寫的字符串是 znvze

ZNVZE 包含元音

半徑為 82 的球體的體積為 2309564.8776326627

6, 53, 82 不能組成三角形。

06、53、82平均47.0

小寫的字符串是 tmiwb

TMIWB 包含元音

半徑為 69 的球體的體積為 1376055.2813841724

93、68、65可以組成一個三角形

93、68、65的平均值是75.333333333333333

到目前為止,這是我的代碼:

with open('Lab5_Data.txt', 'r') as my_file:
    for line in my_file:
        data = line.split()
        print(line)

for line in my_file:
    line = line[0:5].lower()
    print('Thr string in lowercase is', line)

for i in my_file:
    if(i== 'A' or i== 'E' or i== "I" or i== 'O' or i== 'U'):
        print('contains vowels')
    else:
        print('does not contain any vowels')

我在拆分每一行時遇到了麻煩,因此當我打印輸出時,它會將每個答案與同一行一起顯示。此外,我很難在不製作一個巨大的 for 循環的情況下嘗試獲取每個答案的函數。如果有人有任何意見可以幫助我,將不勝感激!

這裡的主要思想是您可以逐行迭代文件,將行拆分為可用的數據塊,然後將正確的塊傳遞給不同的函數。這將是一個單一的大循環,但每個單獨的計算都將在單獨的函數中完成,因此有助於模塊化。

現在,函數有很多方法,以及如何處理輸出和打印:您可以避免在函數內部打印;您可以返回整個答案字符串;您可以只返回計算值而不是文本字符串;你可以完全在外面處理琴弦;等等。我想你明白了。

我將根據您的喜好保留該級別的自定義。我不想讓代碼過於復雜,所以我保持盡可能簡單和合理的可讀性,有時會犧牲一些更 Pythonic 的方式。

# Here the functions that will be used later in the main loop
# These functions will calculate the answer and produce a string
# Then they will print it, and also return it

def make_lowercase(s):
    answer = s.lower()
    print(answer)
    return answer


def has_vowels(word):
    # For each vowel, see if it is found in the word
    # We test in lowercase for both
    answer = 'Does not contain vowels'
    for vowel in 'aeiou':
        if vowel in word.lower():
            answer = 'Contains vowels'
            break
    print(answer)
    return answer


def calculate_sphere_volume(radius):
    # Remember to convert radius from string to number
    import math
    volume = 4.0/3.0 * math.pi * float(radius)**3
    answer = "The volume of the sphere with radius {} is {}".format(radius, volume)
    print(answer)
    return answer


def check_possible_triangle(a1, b1, c1):
    # Remember to convert from string to number
    a = float(a1)
    b = float(b1)
    c = float(c1)
    answer = '{}, {}, {} can make a triangle'.format(a1, b1, c1)
    if (a + b <= c) or (a + c <= b) or (b + c <= a):
        answer = '{}, {}, {} cannot make a triangle'.format(a1, b1, c1)
    print(answer)
    return answer


def calculate_average(a1, b1, c1):
    # Remember to convert from string to number
    a = float(a1)
    b = float(b1)
    c = float(c1)
    average = (a + b + c) / 3
    answer = 'The average of {}, {}, {} is {}'.format(a1, b1, c1, average)
    print(answer)
    return answer

with open('Lab5_Data.txt', 'r') as my_file:    
    for line in my_file:
        # if you split each line, you get the individual elements
        # you can then group them appropriately, like so:
        # word: will contain the 5 letter string
        # radius: will be the first number, to be used for the sphere
        # a,b,c will be the three numbers to check for triangle
        # Important: THESE ARE ALL STRINGS!
        word, radius, a, b, c = line.split()

        # Now you can just use functions to calculate and print the results.
        # You could eliminate the prints from each function, and only use the
        # return results that will be combined in the end.

        # Lowercase:
        ans1 = make_lowercase(word)

        # Does this word have vowels?
        ans2 = has_vowels(word)

        # Calculate the sphere volume
        ans3 = calculate_sphere_volume(radius)

        # Check the triangle
        ans4 = check_possible_triangle(a, b, c)

        # Calculate average
        ans5 = calculate_average(a, b, c)

        # Now let's combine in a single line
        full_answer = '{} {} {} {} {}'.format(ans1, ans2, ans3, ans4, ans5)
        print(full_answer)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

無法讀取文件內容

如何從 PJSIP 頭文件中讀取特定內容(sip info request)?

從 Inno Setup 安裝程序中讀取文件的內容

Java:為什麼我的代碼讀取和保存文件路徑而不是文件的實際內容?

BeautifulSoup [python] 在特定點之後不從 <td> 標籤讀取內容

有沒有辦法根據內容從列表中讀取成員?

在 VSCode 擴展中,如何使用從另一個文件讀取的內容填充未命名的未保存文件?

如何使用bash讀取文件然後執行

在 Python 中讀取位於 S3 子文件夾下的文件的內容

如何用反斜杠和空格“\”替換空格,以便 bash shell 腳本可以從 .tsv 文件中讀取文件名並執行 rsync 複製

如何使用 PHP 讀取大 gz 文件的部分內容

如何讀取 Azure DevOps Agent 的主機文件內容?

使用 if 語句檢查內容類型以確定要執行的操作

CS1929 - 嘗試讀取文件,並跳到包含某個字符串的行並返回該行的內容

在 Python 中從 FTP 讀取 CSV 文件不讀取所有行

讀取文件並將文件中沒有註釋的相同內容保存在新文件中

如何從任何 div 獲取內容值以使用 JQuery 進行計算?

是否有 Node.js 函數來讀取服務器上文件的內容?

將文件內容讀入dict python

試圖將文件內容讀入數組,但內容以冒號分隔

Python - 從 file.readlines() 讀取和操作列表在 for 循環中的行為與在 while 循環中的行為不同

如何強制 R 執行引號內的內容?

在C中逐行從文件中讀取整數和字符

如何從數據文件中讀取指定間隔的行?

從文件中刪除行,在循環讀取 python 中

從 csv 文件中讀取,並刪除任何只有 "" 的行

C++ 從文件中讀取特定範圍的行

僅在 hastag 符號 Python 之後從文件中讀取行:

從 CSV 文件讀取的字典中對結果進行排序