by imaginenore · 9y ago · 0 comments
One-line that reads the file, splits multiple lines into an array:
<?php
$l = explode("\n", file_get_contents("in.txt"));
Want to sort them alphabetically? Add sort($l);
Trim them? $trimmed = array_map(trim, $l);
Remove duplicates? $unique = array_unique($trimmed);List<string> lines = File.ReadAllLines("/file.txt").Distinct().ToList().Select(l => l.Trim()).Sort();
with open("foo.txt.") as f: foo = sorted(list(set(line.strip() for line in f])))
with is a context manager that will automatically close the file once it's out of scope, not required but it's much cleaner and safer. Should the code change you don't have to worry about the call to close the file getting lost. The call to set() could be replaced with a set comprehension, {i for i in sequence}, but for clarity I used set().
It's certainly not the most efficient way to do it but it's simple and clear.
File.read("in.txt").split("\n").sort.map(&:trim).uniq
No need for X temporary variables and N lines of code in ruby.Also notice the better readability as everything happens from left to right?
$l = file('in.txt', FILE_IGNORE_NEW_LINES);