Skip to main content
 首页 » 编程设计

python阅读整个段落而不是阅读行

2025年05月04日15lidabo

这是我的代码:

with open(root_dir+"/trials/classify/training_queries.txt","r") as f: 
        queries = f.readlines() 
        #queries = f.read() 

上面的代码从文件中逐行读取内容,并针对我的案例给出每一行的结果。

我想显示整个文件内容的结果(一次读取整个段落),它的功能是什么?

我认为 queries = f.read() 会有所帮助,但它会逐个字符地考虑。

更新

示例输入:

Hell, the Orioles' Opening Day game could easily be the largest in history 
if we had a stadium with 80,000 seats. But unfortunely the Yards (a 
definitely excellent ballpark) only holds like 45,000 with 275 SRO spots. 
Ticket sales for the entire year is moving fast. Bleacher seats are almost 
gone for every game this year. Athist does not believe in any religion whether hinduis islam or chirstianism 

输出场景:

对于 readLine() - 它是逐行处理

我想做的是考虑整个文件内容。

代码片段:

if __name__ == '__main__': 
    #CallDomainDetection().callDomainDetection(sys.argv[1]) 
    root_dir = os.getcwd() 
    query_no = 1 
    with open(root_dir+"/trials/classify/training_queries.txt","r") as f: 
        #queries = f.readlines()  # this processes line in files 
        queries = f.read()    # now it consider each character.  
    for qu in queries: 
        CallDomainDetection().callDomainDetection(qu) 
        if query_no == 40: 
            break 
        query_no += 1 

请您参考如下方法:

f.read() 就是你想要的。您可能需要用两个换行符将其拆分为多个段落 - split('\n\n')。你所描述的听起来像是在迭代字符串本身——这意味着逐个字符迭代。