Python新手求助:如何根据行列值从CSV获取特定单元格值
Hey there! Since you're new to Python, let's walk through how to pull Mike's review from that CSV file. It's totally doable with Python's built-in tools—no fancy libraries needed!
The easiest way for beginners is to use Python's built-in csv module. It handles all the CSV formatting details (like quoted text) for you, and lets you access data by column names which is way more intuitive than counting columns.
Step-by-Step Code (Reading from a CSV File)
First, save your sample data into a file named hotels.csv. Then use this code:
import csv # Open the CSV file safely using a 'with' block (it auto-closes the file for you) with open('hotels.csv', mode='r') as csv_file: # Create a DictReader object—this turns each row into a dictionary with column headers as keys csv_reader = csv.DictReader(csv_file) # Loop through every row in the CSV for row in csv_reader: # Check if the 'user' column matches 'mike' if row['user'].lower() == 'mike': # Using .lower() to avoid case sensitivity (e.g., 'Mike' would also work) # Print out Mike's review print("Mike's Review:", row['review'])
What This Code Does:
csv.DictReader: Converts each row into a dictionary where you can use column names (likerow['user']orrow['review']) to access values—no need to remember which column index is which!with open(...): This is the safest way to handle files in Python. It automatically closes the file once we're done, so you don't have to worry about forgettingcsv_file.close().- The loop checks each row's
uservalue, and when it finds 'mike', it grabs the correspondingreviewvalue and prints it.
Bonus: Test with Sample Data Directly (No File Needed)
If you don't want to save the CSV to a file and just want to test with your sample data, you can use StringIO to treat the CSV string as a file:
import csv from io import StringIO # Your sample CSV content as a string sample_csv = """user,hotel_name,city,review adam,hotel1,chennai,"Wow, what charm! As a Travel Agent." john,hotel2,pune,Great location for sporting events. mike,hotel3,mumbai,Its the best of the best. george,hotel4,delhi,Ok hotel in a bad location.""" # Use StringIO to simulate a file with StringIO(sample_csv) as csv_file: csv_reader = csv.DictReader(csv_file) for row in csv_reader: if row['user'] == 'mike': print("Mike's Review:", row['review'])
When you run either of these codes, you'll get the output:
Mike's Review: Its the best of the best.
内容的提问来源于stack exchange,提问作者avi

