如何在Python中创建四列表格?现有数据与代码问题求助
First, here's the markdown table formatted from your sample bird data:
| Common Name | Scientific Name | Marathi Name |
|---|---|---|
| Little Grebe | Tachybaptus ruficollis | टीबुकली |
| Great Crested Grebe | Podiceps cristatus | मोठी टीबुकली |
| Black-necked Grebe | Podiceps nigricollis | काळया मानेची टीबुकली |
| Spot-billed Pelican | Pelecanus philippensis | ठीपक्याच्या चोचीचा झोळीवाला |
Now, let's fix your Python code. The issue with your current approach is using readline(30) which reads arbitrary chunks of 30 characters instead of properly parsing each line's three fields. Since scientific names are always two Latin words, and Marathi names use Devanagari script, we can split each line logically into the three components:
with open("test.txt", "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue # Skip empty lines # Remove the leading number and dot (e.g., "1. ") if ". " in line: content = line.split(". ", 1)[1] else: content = line # Split into individual words words = content.split() # Separate Latin (common/scientific) and Marathi words latin_words = [] marathi_words = [] for word in words: # Check if word is Latin (ASCII characters only) if all(ord(c) < 128 for c in word): latin_words.append(word) else: marathi_words.append(word) # Extract the three fields common_name = " ".join(latin_words[:-2]) # All Latin except last two scientific_name = " ".join(latin_words[-2:]) # Last two Latin words (binomial name) marathi_name = " ".join(marathi_words) # Print tab-separated columns print(f"{common_name}\t{scientific_name}\t{marathi_name}")
Key improvements in this code:
- Uses
withstatement to handle file closure automatically (safer than manualopen/close) - Processes each line individually instead of hardcoding 2210 lines
- Logically splits fields based on script type (Latin vs Devanagari) and scientific name structure (two words)
- Handles empty lines gracefully
- Uses UTF-8 encoding to properly read Marathi characters
This should output exactly the tab-separated format you need for each bird entry.
内容的提问来源于stack exchange,提问作者CheaterLetsGO
相关产品推荐
相关产品推荐

