Skip to content

Commit 233186c

Browse files
authored
Merge pull request sumanth-0#794 from akashadsare/add-simple-markdown-converter
Add Simple Markdown Converter - Issue sumanth-0#789
2 parents d7f9d04 + df04a9b commit 233186c

File tree

2 files changed

+187
-0
lines changed

2 files changed

+187
-0
lines changed
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Simple Markdown Converter
2+
3+
A minimal Python script that converts plain text files to markdown format with automatic header and bullet list detection.
4+
5+
## Features
6+
7+
- **Header Detection**: Lines ending with `:` become `## Headers`
8+
- **Bullet Lists**: Lines starting with `-`, `*`, or `` become markdown bullets
9+
- **Numbered Lists**: Lines starting with numbers become ordered lists
10+
- **Auto Output**: Automatically names output file with `.md` extension
11+
- **Sample Generation**: Creates sample file for testing
12+
13+
## Usage
14+
15+
### Command Line
16+
```bash
17+
python markdown_converter.py input.txt [output.md]
18+
```
19+
20+
### Interactive Mode
21+
```bash
22+
python markdown_converter.py
23+
```
24+
25+
## Conversion Rules
26+
27+
| Input | Output |
28+
|-------|--------|
29+
| `Header:` | `## Header` |
30+
| `- Item` | `- Item` |
31+
| `* Item` | `- Item` |
32+
| `• Item` | `- Item` |
33+
| `1. Item` | `1. Item` |
34+
| `Regular text` | `Regular text` |
35+
36+
## Example
37+
38+
**Input (sample.txt):**
39+
```
40+
Introduction:
41+
This is a sample document.
42+
43+
Features:
44+
- Easy to use
45+
- Fast conversion
46+
* Multiple bullet styles
47+
48+
Steps:
49+
1. Open file
50+
2. Run converter
51+
```
52+
53+
**Output (sample.md):**
54+
```markdown
55+
## Introduction
56+
This is a sample document.
57+
58+
## Features
59+
- Easy to use
60+
- Fast conversion
61+
- Multiple bullet styles
62+
63+
## Steps
64+
1. Open file
65+
1. Run converter
66+
```
67+
68+
## Requirements
69+
70+
- Python 3.6+
71+
- No external dependencies
72+
73+
## Author
74+
75+
Created for issue #789 - 100 Lines of Python Code Project
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
#!/usr/bin/env python3
2+
import os
3+
import sys
4+
import re
5+
6+
7+
def convert_to_markdown(text):
8+
"""Convert plain text to markdown format."""
9+
lines = text.split('\n')
10+
markdown_lines = []
11+
12+
for line in lines:
13+
line = line.strip()
14+
if not line:
15+
markdown_lines.append('')
16+
continue
17+
18+
# Convert headers (lines ending with :)
19+
if line.endswith(':'):
20+
markdown_lines.append(f"## {line[:-1]}")
21+
# Convert bullet points (lines starting with -, *, or •)
22+
elif line.startswith(('-', '*', '•')):
23+
content = line[1:].strip()
24+
markdown_lines.append(f"- {content}")
25+
# Convert numbered lists
26+
elif re.match(r'^\d+\.?\s+', line):
27+
content = re.sub(r'^\d+\.?\s+', '', line)
28+
markdown_lines.append(f"1. {content}")
29+
# Regular text
30+
else:
31+
markdown_lines.append(line)
32+
33+
return '\n'.join(markdown_lines)
34+
35+
36+
def process_file(input_file, output_file=None):
37+
"""Process input file and convert to markdown."""
38+
try:
39+
with open(input_file, 'r', encoding='utf-8') as f:
40+
content = f.read()
41+
42+
markdown_content = convert_to_markdown(content)
43+
44+
if not output_file:
45+
output_file = os.path.splitext(input_file)[0] + '.md'
46+
47+
with open(output_file, 'w', encoding='utf-8') as f:
48+
f.write(markdown_content)
49+
50+
print(f"Converted: {input_file} -> {output_file}")
51+
return True
52+
53+
except FileNotFoundError:
54+
print(f"Error: File not found: {input_file}")
55+
return False
56+
except Exception as e:
57+
print(f"Error: {e}")
58+
return False
59+
60+
61+
def create_sample_file():
62+
"""Create a sample text file for demonstration."""
63+
sample_content = """Introduction:
64+
This is a sample document.
65+
66+
Features:
67+
- Easy to use
68+
- Fast conversion
69+
- Supports headers
70+
* Multiple bullet styles
71+
• Unicode bullets too
72+
73+
Steps to follow:
74+
1. Open the file
75+
2. Run the converter
76+
3. Check the output
77+
78+
Conclusion:
79+
The conversion is complete."""
80+
81+
with open('sample.txt', 'w', encoding='utf-8') as f:
82+
f.write(sample_content)
83+
print("Created sample.txt")
84+
85+
86+
def main():
87+
"""Main function."""
88+
print("Simple Markdown Converter")
89+
print("=" * 30)
90+
91+
if len(sys.argv) > 1:
92+
input_file = sys.argv[1]
93+
output_file = sys.argv[2] if len(sys.argv) > 2 else None
94+
else:
95+
input_file = input("Enter input file path (or press Enter for sample): ").strip()
96+
97+
if not input_file:
98+
create_sample_file()
99+
input_file = 'sample.txt'
100+
101+
output_file = input("Enter output file path (optional): ").strip() or None
102+
103+
if not os.path.exists(input_file):
104+
print(f"File not found: {input_file}")
105+
return
106+
107+
if process_file(input_file, output_file):
108+
print("Conversion completed successfully!")
109+
110+
111+
if __name__ == "__main__":
112+
main()

0 commit comments

Comments
 (0)