简体   繁体   English

Python:如何从特定的文本行中获取字数并保存以对其进行计算

[英]Python: How do I get the word count from a specific line of text and save it to do calculations on it

I am trying to count the number of words in a file and then I want to do some calculations of those numbers. 我试图计算文件中的单词数,然后对这些数字进行一些计算。 Right now, this code will only save the last line of code. 现在,此代码将只保存最后一行代码。 How can I get this to work? 我该如何工作?

def fileVerify():
    start = 0
    while start == 0:
        fileName = input("Please enter the name of the file you want to open ")
        try:
            inFile = open(fileName, "r")
            inFile.close()
            start = 1
        except Exception as ex:
            print("Could not open ", fileName)
            print("  Actual exception error message is:")
            print("  "+str(ex))
        return fileName


def readFile(fileName):
    inFile = open(fileName, "r")
    count = 1
    for lineOfText in inFile:
        print(count,": ",lineOfText,end="")
        count = count + 1
        print("   >>", wordCount(lineOfText), "words")
    return lineOfText


def wordCount(sentence):
    wordCount=0
    sentence=sentence.strip( )
    for i in range (0, len(sentence)):
        if (sentence[i]==" "):
            wordCount=wordCount+1
    if (len(sentence)>0):
        wordCount=wordCount+1
        return wordCount


def wordAverage(a,b):
    average = a/b
    print("The average words per lines are",average)


def minWords(x,y,z):
    if x<=y and x<=z:
        print("Least words in a line:", x)
    elif y<=x and y<=z:
        print("Least words in a line:", y)
    else:
        print("Least words in a line:", z)


def maxWords(x,y,z):
    if x>=y and x>=z:
        print("Most words in a line:", x)
        return x
    elif y>=x and y>=z:
        print("Most words in a line:", y)
        return y
    else:
        print("Most words in a line:", z)
        return z


def totalWords(x,y,z):
    total=x+y+z
    print("Total words in input: ", total)


def totalLines(fileName):
    inFile = open(fileName, "r")
    count = 1
    for lineOfText in inFile:
        count = count + 1
    inFile.close()
    return count

This is my main. 这是我的主力。 I am trying to get x to be the first input, y to be the next, and z to be my last. 我试图让x作为第一个输入,y作为下一个输入,z作为我的最后一个输入。

#main

print("Welcome to file analysis")

fileName=fileVerify()
sent=readFile(fileName)

x=wordCount(sent)
y=wordCount(sent)
z=wordCount(sent)

print("\nAnalysis")
print("===========")

minWords(x,y,z)
a=maxWords(x,y,z)
b=totalLines(fileName)
wordAverage(a, b)
totalWords(x,y,z)

There's a potentially easier way to count words. 有一种可能更容易计数字的方法。 Rather than counting the number of spaces in your sentence, you could create a list based upon splitting the sentence, like so: 您无需计算句子中的空格数,而可以基于拆分句子来创建列表,如下所示:

    >>> sentence = "The quick brown fox jumped over the lazy dog."
    >>> splitSentence = sentence.split()
    >>> splitSentence
    ['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog.']
    >>> len(splitSentence)
    9

.split() is a string method that creates a list from the original string by splitting up the string wherever it finds a space (by default) or a substring of your choice (for example, .split(",") would split on commas). .split()是一个字符串方法,该方法通过在发现空格(默认情况下)或您选择的子字符串(例如,.split(“,”)将在逗号)。 You can test the subsequent list for its length very easily. 您可以很容易地测试后续列表的长度。

words = len(sentence.split())

words将是字符串sentence中单词的数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从Python中的特定文本行中提取文本? - How do I pull text from a specific text line in Python? 如何从 python 中的文本文件中删除特定行 - How do I remove a specific line from a text file in python 如何从Python Requests / Beautiful Soup中的某些文本参数获取HTML的特定行 - How do I get specific line of HTML from certain text parameter in Python Requests/Beautiful Soup 如何从文本文件中删除带有特定单词的整行? - How do I remove an entire line with a specific word, from a text file? 逐行读取文本文件,并从一行中计算特定单词的特定值,并将该行保存在该行上方 - Read text file line by line and Count specific word for particular values from a line and save the line above that 如果单词在字典中,我如何计算每行中的单词出现次数 - How do I count word occurrence in each line if the word is in a dictionary 如何使用 python 仅将 URL 中的特定文本行保存到 txt 文件? - How do I save only specific lines of text from a URL to a txt file using python? 如何将特定文本保存在 .txt 文件中的数组中 - How do I save specific text in an array from .txt file 如何在Python Gtk中进行计算? - How do i do calculations in Python Gtk? 如何使用python从文本中提取准确的单词? - How do I extract an exact word from text by using python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM