首页 > 解决方案 > 使用 Python3 在文件中查找表达式

问题描述

我正在用python3编写一个大学程序。该程序接受用户表达式和文件路径,然后在文件中找到包含该表达式的任何行。我现在的问题如下。

我有一个小的虚拟 txt 文件我用来测试它。该文件包含:

Hello, My name is Evan
This is a text file
I am using it to help me code my program
I am coding my program in Python3

我的主要Python文件如下:

# Necessary imports
import os

# Variables
userExpression = [] # Variable for user expression
userFile = [] # Variable for user file
fileLines = [] # Variable for lines of text in the users file
lineNum = 0 # Variable for keeping track of line numbers

userExpression = input("Please enter the expression you want to find: ") # Read in and store users expression
userFile = input("Enter the path of your file: ") # Read in and store file path of users file

myFile = open(userFile) # Opening user file

print("                                                          ") # Used to make output easier to read
print("HOORAY!! File found!")
print("File lines that include your expressions are found below: ")
print("                                                          ") # Used to make output easier to read

# Store each line of text into a list
for line in myFile:
    lineNum += 1
    if line.lower().find(userExpression) != -1:
        fileLines.append("Line " + str(lineNum) + ": " + line.rstrip('\n'))

# Print out file text stored in list
for element in fileLines:
    print(element)

myFile.close()

对于我的一项测试,我输入了“am”作为我想要查找的表达式。我得到了这个作为输出:

HOORAY!! File found!
File lines that include your expressions are found below:

Line 1: Hello, My name is Evan
Line 3: I am using it to help me code my program
Line 4: I am coding my program in Python3

问题是我的程序退出了第 1 行,因为 'name' 包含 'am'。有什么办法可以修复它,只输出第 3 行和第 4 行,因为它们特别包含“am”

标签: python-3.x

解决方案


也许尝试检测“userExpression”(带空格),所以程序只能自己获取“userExpression”。

    #like this
    userExpression = " " + input("Please enter the expression you want to find: ") + " "

推荐阅读